matlab实现rgb和hsi互转
时间: 2023-11-02 10:02:33 浏览: 202
RGB与HSI转换matlab实现
4星 · 用户满意度95%
以下是Matlab中RGB与HSI的互相转换的代码实现:
RGB转HSI:
```matlab
function [H, S, I] = RGB2HSI(R, G, B)
% 将 RGB 值转换为 HSI 值
% R, G, B 取值范围 [0, 1]
% H 取值范围 [0, 2*pi]
% S, I 取值范围 [0, 1]
% 将 RGB 值归一化到 [0, 1] 范围内
R = double(R)/255;
G = double(G)/255;
B = double(B)/255;
I = (R + G + B)/3;
S = 1 - min(R, min(G, B))./I;
if S == 0
H = 0;
elseif B <= G
H = acos(0.5*(2*R - G - B)./(sqrt((R - G).^2 + (R - B).*(G - B))) + eps);
else
H = 2*pi - acos(0.5*(2*R - G - B)./(sqrt((R - G).^2 + (R - B).*(G - B))) + eps);
end
end
```
HSI转RGB:
```matlab
function [R, G, B] = HSI2RGB(H, S, I)
% 将 HSI 值转换为 RGB 值
% H 取值范围 [0, 2*pi]
% S, I 取值范围 [0, 1]
% R, G, B 取值范围 [0, 255]
if H >= 0 && H < 2*pi/3
B = I.*(1 - S);
R = I.*(1 + S.*cos(H)./cos(pi/3 - H));
G = 3*I - (R + B);
elseif H >= 2*pi/3 && H < 4*pi/3
H = H - 2*pi/3;
R = I.*(1 - S);
G = I.*(1 + S.*cos(H)./cos(pi/3 - H));
B = 3*I - (R + G);
elseif H >= 4*pi/3 && H < 2*pi
H = H - 4*pi/3;
G = I.*(1 - S);
B = I.*(1 + S.*cos(H)./cos(pi/3 - H));
R = 3*I - (G + B);
end
% 将 RGB 值归一化到 [0, 255] 范围内
R = round(R*255);
G = round(G*255);
B = round(B*255);
end
```
使用方式:
```matlab
% RGB 转 HSI
R = 100;
G = 150;
B = 200;
[H, S, I] = RGB2HSI(R, G, B);
% HSI 转 RGB
[R, G, B] = HSI2RGB(H, S, I);
```
其中,RGB值的范围为 [0, 255],HSI值的范围为 [0, 1]。
阅读全文