如何通过Matlab以百分比计算图像的每个RGB颜色通道的亮度?

问题描述:

如何通过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.

不知道如何解决这个问题?

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'。 –