2017-02-22 5 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 ; 

私は、B.

どのように問題を解決するために、任意のアイデアを、各チャンネルR、Gの強度割合を見ることができませんでしたか?

答えて

3

MATLABは除算後にデータ型を保存します。 rval,gval、およびbvalは元々int64として保存されているため、このユニットタイプは,,G_total,B_totalおよびI_totalに伝播されます。これらの値を分割してパーセンテージを求めようとすると、除算操作が最初に実行されます(乗算と除算などの演算の優先順位が同じ場合、MATLABは左から右へ動作します)。この分割の結果はint64ユニットタイプを保持します。個々のカラーチャンネルの合計が合計よりも小さいので、その結果は0と1の間の値になります。整数は浮動小数点数を保存できないため、結果はゼロまたは1に丸められます。そもそも二重のようrvalbval、およびgval変数を

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

または代替として保存:正しくまず、パーセンテージを見つけるために、これらの数字を分けるなどのダブルユニットタイプにそれらを変換するために

MATLABの行列ベクトル化(行列の最後に(:)を追加すると、行列を積み重ねることによって行列がベクトルに変換されます)や組み込み関数などを利用することで、コードを大幅に改善できますsumとなります。ボーナスとして、sumは、デフォルトではその結果を2倍に累積し、各値を手動で変換する必要がなくなります。

簡略化されたコードは次のようになります。

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なぜ二重に変換するのですか? 'sum'は整数を入力として扱うことに問題はなく、デフォルトでは' double'を返します。 –

関連する問題