【问题标题】:How to calculate the intensity of each RGB color channel of an image as a percentage via Matlab?如何通过Matlab将图像的每个RGB颜色通道的强度计算为百分比?
【发布时间】:2017-07-12 15:19:12
【问题描述】:

如何通过 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 的强度百分比。

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

【问题讨论】:

    标签: image matlab colors rgb


    【解决方案1】:

    MATLAB 保留除法后的数据类型。因为rval、gval和bval最初保存为int64,所以这个单元类型传播到R_total、G_total、B_total和I_total。当您尝试将这些值相除以求百分比时,首先执行除法运算(当运算具有相同的优先级(例如乘法和除法)时,MATLAB 从左到右工作)。此除法的结果保留int64 单位类型。因为单个颜色通道的总数小于总数,所以结果是一个介于 0 和 1 之间的值。由于整数无法保存浮点数,因此将结果四舍五入为零或一。

    为了正确划分这些数字以求出百分比,首先将它们转换成双精度单位类型如:

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

    或者将 rval、bval 和 gval 变量保存为 double 开头。

    顺便说一句,您的代码可以通过利用 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 ;
    

    【讨论】:

    • 在求和之前不要忘记转换为双精度。
    • @gnovice 你为什么要先转换成双倍? sum 将整数作为输入没有问题,默认情况下会返回 double。
    • 啊,我想知道这是否是 sum 的新行为。我记得在处理整数时不得不担心饱和,但我想现在不再是这种情况了。
    猜你喜欢
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多