数字图像处理:RGB 与 HSI 模型转换 Matlab 程序
im1=imread('Fig6.30(01).jpg');
im3=im1;
im1=im2double(im1);
[m,n,q]=size(im1);
% 获取图像的 RGB 3 个通道
R=im1(:,:,1);
G=im1(:,:,2);
B=im1(:,:,3);
% 改变通道来观察图像
figure,subplot(1,3,1),imshow(cat(3,R*0.5,G,B)),title('R 通道减半');
set(gcf,'outerposition',get(0,'screensize'));
set(gcf,'NumberTitle','off','Name','改变通道来观察图像');
subplot(1,3,2),imshow(cat(3,R,G*2,B)),title('G 通道翻倍');
subplot(1,3,3),imshow(cat(3,R,G,zeros(m,n))),title('B 通道为 0');
% 观察 HSI 通道图像
% 因系统没有 rgb2hsi 函数,只有 rgb2hsv 函数,所以自己编写程序实现
H=zeros(m,n);
S=H;
for i1=1:m
for i2=1:n
numerator=0.5*(R(i1,i2)-G(i1,i2)+R(i1,i2)-B(i1,i2));
denominator=sqrt((R(i1,i2)-G(i1,i2))^2+(R(i1,i2)-B(i1,
i2))*(G(i1,i2)-B(i1,i2)));
theta=acos(numerator/denominator)*180/pi;
if(B(i1,i2)<=G(i1,i2))
H(i1,i2)=theta;
else
H(i1,i2)=360-theta;
end
min1=min(R(i1,i2),G(i1,i2));
min1=min(B(i1,i2),min1);
S(i1,i2)=1-3/(R(i1,i2)+G(i1,i2)+B(i1,i2))*min1;
end
end
I=(R+G+B)/3;
figure,subplot(1,3,1),imshow(H,[]),title('色度图 H');
set(gcf,'outerposition',get(0,'screensize'));
set(gcf,'NumberTitle','off','Name','HSI 通道图像');
subplot(1,3,2),imshow(S),title('饱和度图 S');
subplot(1,3,3),imshow(I),title('强度图 I');
% 从 HSI 转换回 RGB 模型并观察图像,系统也不自带 hsi2rgb,仅自带 hsv2rgb
im2=zeros(m,n,3);
for i1=1:m
for i2=1:n
value1=I(i1,i2)*(1+S(i1,i2)*cos(H(i1,i2))/cos(pi/3-H(i
1,i2)/180*pi));
value2=I(i1,i2)*(1-S(i1,i2));
switch (floor(H(i1,i2)/120))
case 0
im2(i1,i2,1)=value1;
im2(i1,i2,2)=3*I(i1,i2)-R(i1,i2)-B(i1,
im2(i1,i2,3)=value2;
case 1
H(i1,i2)=H(i1,i2)-120;
im2(i1,i2,1)=value2;
im2(i1,i2,2)=value1;
im2(i1,i2,3)=3*I(i1,i2)-R(i1,i2)-G(i1,
case 2
H(i1,i2)=H(i1,i2)-240;
im2(i1,i2,1)=3*I(i1,i2)-G(i1,i2)-B(i1,
im2(i1,i2,2)=value2;
im2(i1,i2,3)=value1;
i2);
i2);
i2);
end
end
end
% 模型转换完毕,显示图像
figure,subplot(1,2,1),imshow(im1),title('原图');
set(gcf,'outerposition',get(0,'screensize'));
set(gcf,'NumberTitle','off','Name','原图与 HSI 转 RGB 通道图像对比');
subplot(1,2,2),imshow(im2),title('HSI 转 RGB 通道图像');
% 给图像添加噪声
im3=imnoise(im3,'salt & pepper',0.02);
R=im3(:,:,1);
G=im3(:,:,2);
B=im3(:,:,3);
R=medfilt2(R);
G=medfilt2(G);
B=medfilt2(B);
im4=cat(3,R,G,B);
figure,subplot(1,3,1),imshow(im1),title('原图');
set(gcf,'outerposition',get(0,'screensize'));
set(gcf,'NumberTitle','off','Name','图像对比');
subplot(1,3,2),imshow(im3),title('加入椒盐噪声后图像');
subplot(1,3,3),imshow(im4),title('中值滤波后图像');