matlab 연습 프로그램(RGB2HSV, HSV2RGB)

6462 단어 matlab
색상 포화도 명도와 삼원색의 상호 전환
clear all;
close all;
clc;

img=imread('lena_color.jpg');
img=mat2gray(img);  %       [0,1];
[m n dim]=size(img);
imshow(img);
%%   RGB
R=img(:,:,1);
G=img(:,:,2);
B=img(:,:,3);

%%   RGB2HSV
H=zeros(m,n);   %   
S=zeros(m,n);   %   
V=zeros(m,n);   %  
for i=1:m
   for j=1:n
       r=R(i,j);
       g=G(i,j);
       b=B(i,j);
       MAX=max([r,g,b]);
       MIN=min([r,g,b]);

       if MAX==MIN
            H(i,j)=0;
       elseif MAX==r && g>=b
            H(i,j)=60*(g-b)/(MAX-MIN);
       elseif MAX==r && g<b
            H(i,j)=60*(g-b)/(MAX-MIN)+360;
       elseif MAX==g
            H(i,j)=60*(b-r)/(MAX-MIN)+120;
       elseif MAX==b
            H(i,j)=60*(r-g)/(MAX-MIN)+240;
       end

       if MAX==0
            S(i,j)=0;
       else
            S(i,j)=1-MIN/MAX;
       end

       V(i,j)=MAX;
   end
end

%%  HSV2RGB
for i=1:m
    for j=1:n
        h=floor(H(i,j)/60);
        f=H(i,j)/60-h;
        v=V(i,j);
        s=S(i,j);
        p=v*(1-s);
        q=v*(1-f*s);
        t=v*(1-(1-f)*s);

        if h==0
            R(i,j)=v;G(i,j)=t;B(i,j)=p;
        elseif h==1
            R(i,j)=q;G(i,j)=v;B(i,j)=p;            
        elseif h==2
            R(i,j)=p;G(i,j)=v;B(i,j)=t;            
        elseif h==3
            R(i,j)=p;G(i,j)=q;B(i,j)=v;            
        elseif h==4
            R(i,j)=t;G(i,j)=p;B(i,j)=v;            
        elseif h==5
            R(i,j)=v;G(i,j)=p;B(i,j)=q;            
        end
    end
end

%%           ,        
img(:,:,1)=R;
img(:,:,2)=G;
img(:,:,3)=B;
figure;
imshow(img)

참조: http://zh.wikipedia.org/wiki/HSV_%E8%89%B2%E5%BD%A9%E7%A9%BA%E9%97%B4#.E4.BB.8E_HSV_.E5.88.B0_RGB_.E7.9A.84.E8.BD.AC.E6.8D.A2

좋은 웹페이지 즐겨찾기