rgb与hsi的相互转换代码
时间: 2024-06-10 11:09:36 浏览: 68
RGB与HSI的相互转换代码如下所示:
RGB转换为HSI:
```
function [H,S,I] = rgb2hsi(colorfig)
colorfig = im2double(colorfig);
R = colorfig(:,:,1);
G = colorfig(:,:,2);
B = colorfig(:,:,3);
theta = acos((0.5*((R-G).*(R-B)))./((R-G).^2 + (R-B).*(G-B)).^0.5 + 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 + G + B)/3;
end
```
HSI转换为RGB:
```
function [R,G,B] = hsi2rgb(hsi)
H = hsi(:,:,1);
S = hsi(:,:,2);
I = hsi(:,:,3);
H = H * 2*pi;
R = zeros(size(H));
G = zeros(size(H));
B = zeros(size(H));
idx1 = (0 <= H) & (H < 2*pi/3);
idx2 = (2*pi/3 <= H) & (H < 4*pi/3);
idx3 = (4*pi/3 <= H) & (H < 2*pi);
B(idx1) = I(idx1).*(1 - S(idx1));
R(idx1) = I(idx1).*(1 + S(idx1).*cos(H(idx1))./cos(pi/3 - H(idx1)));
G(idx1) = 3*I(idx1) - (R(idx1) + B(idx1));
R(idx2) = I(idx2).*(1 - S(idx2));
G(idx2) = I(idx2).*(1 + S(idx2).*cos(H(idx2) - 2*pi/3)./cos(pi - H(idx2)));
B(idx2) = 3*I(idx2) - (R(idx2) + G(idx2));
G(idx3) = I(idx3).*(1 - S(idx3));
B(idx3) = I(idx3).*(1 + S(idx3).*cos(H(idx3) - 4*pi/3)./cos(5*pi/3 - H(idx3)));
R(idx3) = 3*I(idx3) - (G(idx3) + B(idx3));
end
```
阅读全文