在看中科院劉定生老師的《數字圖像處理與分析》的課程,講到顔色模型的應用時布置了一個作業,利用HIS模型特性消除紅眼。今天先解決圖像的空間轉換問題:
顔色模型之間的轉換RGB→HSI。
給出一幅RGB彩色格式的圖像,那麼每個RGB像素的H分量可用下面的公式得到:
M-檔案函數代碼部分:
function hsi=rgb2hsi(rgb)
%RGB2HSI Converts an RGB image to HSI
% HSI=RGB2HSI(rgb) converts an RGB image to HSI. The input image is
% assumed to be of size M-by-N-by-3, where the third dimension accounts
% for three image planes:red, green, and blue, in that order. If all RGB
% component images are equal, the HSI conversion is undefined. Ths input
% image can be of class double (with values in the rang[0,1]), uint8, or
% uint16.
% The output image, HSI, is of class double, where:
% hsi(:,:,1)= hue image normalized values to the range [0,1] by
% dividing all angle values by 2*pi.
% hsi(:,:,2)=saturation image, in the range [0,1].
% hsi(:,:,3)=intensity image, in the range [0,1].
%Extract the individual component images.
rgb=im2double(rgb);
r=rgb(:,:,1);
g=rgb(:,:,2);
b=rgb(:,:,3);
%Implement the conversion equations.
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+g+b)/3;
%Combine all three results into an hsi image.
hsi=cat(3,H,S,I);
顔色模型之間的轉換HSI→RGB
在[0,1]内給出HIS值,現在要在相同的值域找到RGB值,可利用H值公式。在原始色分割中有3個相隔120度的扇形,從H乘以360開始,這時色調值傳回原來的[0,360]的範圍。
RG扇形(0<H<120):當H位于這一扇形區時,RGB分量由下式給出:
GB扇區(120<H<240):如果給定的H值在這一扇區,首先從H中減去120,即:H=H-120
然後RGB分量為:
BR扇區(240<H<360):最後,如果H在這一扇區,從H中減去240:H=H-240
然後RGB分量為:
M-檔案函數代碼部分:
function rgb = hsi2rgb(HSI)
% 将圖像從HSI空間轉換到RGB空間
% 輸入參數為hsi圖像,輸出變量為rgb
% 分别取出H、S、I分量
H=HSI(:,:,1)*2*pi;
S=HSI(:,:,2);
I=HSI(:,:,3);
% 定義R、G、B三個矩陣大小
R=zeros(size(H));%size(H)求矩陣H的行列數,傳回2個向量,第一個是行數,第二是列數
G=zeros(size(H));
B=zeros(size(H));
% H在[0,120°)區間
sy=find((0<=H)&(H<2*pi/3));
B(sy)=I(sy).*(1-S(sy));
R(sy)=I(sy).*(1+S(sy).*cos(H(sy))./cos(pi/3-H(sy)));
G(sy)=3*I(sy)-(R(sy)+B(sy));
% H在[120°,240°)區間
sy=find((2*pi/3<=H)&(H<4*pi/3));
R(sy)=I(sy).*(1-S(sy));
G(sy)=I(sy).*(1+S(sy).*cos(H(sy)-2*pi/3)./cos(pi-H(sy)));
B(sy)=3*I(sy)-(R(sy)+G(sy));
% H在[240°,360°)區間
sy=find((4*pi/3<=H)&(H<2*pi));
G(sy)=I(sy).*(1-S(sy));
B(sy)=I(sy).*(1+S(sy).*cos(H(sy)-4*pi/3)./cos(5*pi/3-H(sy)));
R(sy)=3*I(sy)-(G(sy)+B(sy));
%級聯,擷取RGB影像
rgb=cat(3,R,G,B);
end
第一次發不知編輯的如何,總之開始就不算遲。:)