2017-02-22 143 views
1

如何通過Matlab以百分比計算圖像的每個RGB顏色通道的亮度? 以下Matlab代碼不能正常工作:如何通過Matlab以百分比計算圖像的每個RGB顏色通道的亮度?

I = imread('3.png'); % read image 

Ir=I(:,:,1); % read red chanel 
Ig=I(:,:,2); % read green chanel 
Ib=I(:,:,3); % bule chanel 

% figure, imshow(I), title('Original image') 
% figure, imshow(Ir), title('Red channel') 
% figure, imshow(Ig), title('Green channel') 
% figure, imshow(Ib), title('Blue channel') 

%% read the size of the 
m = size(I,1); 
n = size(I,2); 


R_total= 0; 
G_total= 0; 
B_total= 0; 

for i = 1:m 
      for j = 1:n 

       rVal= int64(Ir(i,j)); 
       gVal= int64(Ig(i,j)); 
       bVal= int64(Ib(i,j)); 

       R_total= R_total+rVal; 
       G_total= G_total+gVal; 
       B_total= B_total+bVal; 

      end  
end 

disp (R_total) 
disp (G_total) 
disp (B_total) 

%% Calcualte the image total intensity 
I_total = R_total + G_total + B_total; 
disp(I_total) 


%% Calculate the percentage of each Channel 

R_precentag = R_total/I_total * 100 ; %% Red Channel Precentage 
G_precentag = G_total/I_total * 100 ; %% Green Channel Precentage 
B_precentag = B_total/I_total * 100 ; 

我無法看到每個通道R,G強度百分比B.

不知道如何解決這個問題?

回答

3

MATLAB保存分割後的數據類型。因爲rvalgval,和bval原本保存爲int64,該單元類型被傳播到R_totalG_totalB_total,和I_total。當您嘗試劃分這些值以查找百分比時,首先執行除法操作(當操作具有相同的優先級時,例如乘法和除法,MATLAB從左向右運行)。該部門的結果保留了int64單位類型。由於單個顏色通道總數小於總數,因此結果爲零和1之間的值。由於整數無法保存浮點數,因此結果取整爲0或1。

爲了正確地把這些數字中尋找百分比,請先將其轉換爲雙單元類型,例如:

R_precentag = double(R_total)/double(I_total) * 100; 

或可替換地保存rvalbvalgval變量雙開始與。另外,通過利用MATLAB的矩陣矢量化(在矩陣的末端添加(:)通過堆疊列將矩陣轉換爲矢量),可以大幅度提高代碼的性能,以及內置函數作爲sum。作爲獎勵,sum將其結果默認爲雙倍結果,無需手動轉換每個值。

例如您的簡化代碼可能類似於:

I = imread('3.png'); % read image 

Ir=I(:,:,1); % read red channel 
Ig=I(:,:,2); % read green channel 
Ib=I(:,:,3); % read blue channel 

R_total= 0; 
G_total= 0; 
B_total= 0; 

R_total = sum(Ir(:)); 
G_total = sum(Ig(:)); 
B_total = sum(Ib(:)); 

disp (R_total) 
disp (G_total) 
disp (B_total) 

%% Calculate the image total intensity 
I_total = R_total + G_total + B_total; 
disp(I_total) 


%% Calculate the percentage of each Channel 
R_precentag = R_total/I_total * 100 ; %% Red Channel Percentage 
G_precentag = G_total/I_total * 100 ; %% Green Channel Percentage 
B_precentag = B_total/I_total * 100 ; 
+0

添加了一個示例,感謝您的建議。 –

+0

不要忘記在進行總和之前將其轉換爲double。 – gnovice

+1

@gnovice爲什麼你會先轉換爲double? 'sum'沒有把整數作爲輸入的問題,默認情況下會返回一個'double'。 –