RGB通道和HSI通道相互转换——MATLAB实现

RGB通道和HSI通道相互转换——MATLAB实现_第1张图片

RGB2HSI.m

function [H,S,I,hsi] = RGB2HSI(RGB_image)
R = RGB_image(:,:,1);
G = RGB_image(:,:,2);
B = RGB_image(:,:,3);

num = 0.5*((R-G)+(R-B));
den =sqrt((R-G).^2 + (R-B).*(G-B)); 
theta = acos(num./(den+eps));

H=theta;
H(B>G)=2*pi - H(B>G);
H=H/(2*pi);

num=min(min(R,G),B);
den=R+G+B;
den(den==0)=eps;
S=1-3.*num./den;

H(S==0)=0;
I=(R+B+G)/3;

hsi=cat(3,H,S,I);
end

RGB通道和HSI通道相互转换——MATLAB实现_第2张图片

HSI2RGB.m

function [rgb] = HSI2RGB(H,S,I)
%%
[w,h] = size(I);

H = H * 2 * pi;%乘以2π的目的是将其从0到1的范围映射到0到360度的角度值
R=zeros(w,h);
G=zeros(w,h);
B=zeros(w,h);

% RG sector(0<= H <2*pi/3)
idx=find((0<=H) & (H<2*pi/3));
B(idx) = I(idx).*(1-S(idx));
R(idx) = I(idx).*(1+S(idx).*cos(H(idx))./cos(pi/3-H(idx)));
G(idx) = 3*I(idx)- (R(idx)+B(idx));

%BG sector(2*pi/3
idx = find((2*pi/3<H)&(H<4*pi/3));
R(idx) = I(idx).*(1-S(idx));
G(idx) = I(idx).*(1+S(idx).*cos(H(idx)-2*pi/3)./cos(pi-H(idx)));
B(idx) = 3*I(idx)- (R(idx)+G(idx));

%BR sector(4*pi/3 
idx = find((4*pi/3<H)&(H<2*pi));
G(idx) = I(idx).*(1-S(idx));
B(idx) = I(idx).*(1+S(idx).*cos(H(idx)-4*pi/3)./cos(5*pi/3-H(idx)));
R(idx) = 3*I(idx)- (G(idx)+B(idx));

rgb = cat(3,R,G,B);
rgb = max(min(rgb,1),0);
end

你可能感兴趣的:(数字图像处理,matlab,数字图像处理)