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

Image 如何通过Matlab计算图像每个RGB颜色通道的强度百分比?,image,matlab,colors,rgb,Image,Matlab,Colors,Rgb,如何通过Matlab计算图像每个RGB颜色通道的强度百分比? 以下Matlab代码无法正常工作: 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),

如何通过Matlab计算图像每个RGB颜色通道的强度百分比? 以下Matlab代码无法正常工作:

    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保存除法后的数据类型。由于
rval
gval
bval
最初保存为
int64
,因此此单位类型将传播到
R\u总计
G\u总计
B\u总计
。当您尝试对这些值进行除法以查找百分比时,首先执行除法运算(当乘法和除法等运算具有相同优先级时,MATLAB从左到右工作)。此除法的结果保留
int64
单位类型。由于单个颜色通道的总计小于总计,因此结果的值介于0和1之间。由于整数不能保存浮点数,因此结果将四舍五入为零或一

为了正确划分这些数字以找到百分比,首先将其转换为双单位类型,例如:

R_precentag = double(R_total) / double(I_total) * 100;
或者将
rval
bval
gval
变量保存为double开始

另外,利用MATLAB的矩阵矢量化(在矩阵末尾添加
(:)
,通过堆叠列将矩阵转换为向量)和内置函数(如
求和
),可以显著改进代码。作为奖励,
sum
在默认情况下将其结果累加为一个双精度,从而无需手动转换每个值

e、 g.您的简化代码可能类似于:

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 ;

在做加法之前别忘了转换成double。@gnovice为什么要先转换成double
sum
将整数作为输入没有问题,默认情况下将返回一个
double
。啊,我想知道这是否是
sum
的新行为。我记得在处理整数时不得不担心饱和,但我想现在已经不是这样了。