具体实现步骤:
function HSI = myRGB2HSI(RGB)
% 从RGB颜色空间向HSI颜色空间的转换
% RGB(uint8):输入的RGB彩色图像
% HSI(double):转换后的HSI彩色图像
img1_double = im2double(RGB); % 转成double并作归一化处理
[r, c, k] = size(img1_double);
H = zeros(r, c);
S = zeros(r, c);
I = zeros(r, c);
for i = 1 : r
for j = 1 : c
% 分别获取R,G,B分量
R = img1_double(i,j,1);
G = img1_double(i,j,2);
B = img1_double(i,j,3);
fenzi = 0.5 * ( (R-G)+(R-B) );
fenmu = sqrt( (R-G)^2 + (R-B)*(G-B) );
% 易错点:分母需加上eps防止为0
xita = acos( fenzi/(fenmu+eps) );
if ( B<=G )
HSI(i,j,1) = xita;
else
HSI(i,j,1) = 2*pi-xita;
end
HSI(i,j,1) = HSI(i,j,1) / (2*pi); % H分量需要除以2*pi进行归一化
min_value = min(min(R,G),B);
% 易错点:分母需加上eps防止为0
HSI(i,j,2) = 1 - ( 3/(R+G+B+eps) ) * min_value;
HSI(i,j,3) = (R+G+B)/3;
end
end
end
具体实现步骤:
function RGB = myHSI2RGB(HSI)
% 从HSI颜色空间向RGB颜色空间的转换
% HSI(double):输入的HSI彩色图像
% RGB(uint8): 转换后的RGB彩色图像
HSI = im2double(HSI);
[r,c,k] = size(HSI);
RGB = zeros(r,c,k);
for i = 1 : r
for j = 1 : c
H = HSI(i,j,1)*2*pi;
S = HSI(i,j,2);
I = HSI(i,j,3);
if ( H>=0 && H<2/3*pi)
expression = S*cos( H )/(cos( pi/3-H ) + eps);
RGB(i,j,1) = I * ( 1+expression );
RGB(i,j,3) = I * (1-S);
RGB(i,j,2) = 3*I - ( RGB(i,j,1)+RGB(i,j,3) );
elseif ( H>=2/3*pi && H<4/3*pi)
H = H-2*pi/3;
RGB(i,j,1) = I * (1-S);
expression = S*cos( H )/(cos( pi/3-H ) + eps);
RGB(i,j,2) = I * ( 1+ expression );
RGB(i,j,3) = 3*I - ( RGB(i,j,1)+RGB(i,j,2) );
elseif (H>=4/3*pi && H<=2*pi)
H = H-4*pi/3;
RGB(i,j,2) = I * (1-S);
expression = S*cos( H )/(cos( pi/3-H ) + eps);
RGB(i,j,3) = I * ( 1+ expression );
RGB(i,j,1) = 3*I - ( RGB(i,j,2)+RGB(i,j,3) );
end
end
end
RGB = RGB * 255;
RGB = uint8(RGB);
end
具体实现步骤:
注意点:提取I分量时要先乘以 255 扩展灰度级,滤波处理完成后要除以 255 再赋值给该 HSI 图像的第三个分量。滤波函数中需采用im2double 读入图像。
clc;
clear all;
img1 = imread('images/EXP5.tif');
subplot(1,2,1);
imshow(img1);
title('输入的 RGB 图像','FontSize',20,'FontName','微软雅黑');
% 1.将rbg图像转换到hsi空间
img_hsi = myRGB2HSI(img1);
% 2.对HSI颜色空间中的亮度分量I进行滤波处理
w = [1,2,3,2,1; 2,5,6,5,2; 3,6,8,6,3; 2,5,6,5,2; 1,2,3,2,1];
i = img_hsi(:,:,3) * 255;
temp = mySpatialFilter(i,[5,5],w);
temp = temp/255;
% 3.将滤波后的结果转回至RGB空间中
img_hsi(:,:,3) = temp;
img2 = myHSI2RGB(img_hsi);
subplot(1,2,2);
imshow(img2);
title('在HSI空间滤波后的图像','FontSize',20,'FontName','微软雅黑');
function img_enhanced = mySpatialFilter( img1 ,fsize, w )
% 均值滤波函数
% img1:输入的rgb图像;img_enhanced:输出图像;fsize:滤波器掩模尺寸
% w:滤波器系数
img1_double = im2double(img1);
[r c] = size(img1_double);
% 获取滤波器模板尺寸
m = fsize(1);
n = fsize(2);
% 补边后的总边数
row_fill = r + m - 1;
col_fill = c + n - 1;
% 用 0 填充边界
img2 = zeros(row_fill, col_fill);
img2(1+(m-1)/2:row_fill-(m-1)/2,1+(n-1)/2:col_fill-(n-1)/2) = img1_double;
img2_copy = img2;
for i = 1 : r
for j = 1 : c
% 提取与滤波器模板等大的区域
img_area = img2_copy(i:i+m-1,j:j+n-1);
x_center = i + (m-1)/2;
y_center = j + (n-1)/2;
% 计算滤波处理后的图像
img2(x_center,y_center) = sum(w(:).*img_area(:))/sum(w(:));
end
end
img_enhanced= img2(1+(m-1)/2:row_fill-(m-1)/2,1+(n-1)/2:col_fill-(n-1)/2);
end