MATLAB CODE FOR COLOUR DETECTION USING CAMERA

%% MATLAB CODE FOR COLOUR DETECTION AND DISPLAYING THE DETECTED COLOUR 
clc
clear all
imaqreset
vidobj=videoinput('winvideo',1); %% using  webcam for capturing %%the image 
%% use vidobj=videoinput('winvideo',2); %%if webcam isn't being %%accessed
while(1) %% continously looping , press Ctrl + C to terminate  
    
    image_ycbcr=getsnapshot(vidobj);       %% Captured image is by                                              %%default in YCBCR color space.
    image_cb=image_ycbcr(:,:,2);
    image_cr=image_ycbcr(:,:,3);
    [r c d]=size(image_ycbcr);
    output_image1=zeros(r,c);
    output_image2=zeros(r,c);
    output_image3=zeros(r,c);
    output_image4=zeros(r,c);
    output_image5=zeros(r,c);
    output_image6=zeros(r,c);
    
    for i=1:r  %% detecting different colours in the image
        for j=1:c
            if(image_cb(i,j)>150&&image_cr(i,j)<140)
                output_image1(i,j)=1;
              
            end
            
           if(image_cb(i,j)<80&&(image_cr(i,j)>145&&image_cr(i,j)<160))
                
                    output_image2(i,j)=1;
                 
           end
           
           if((image_cb(i,j)>80&&image_cb(i,j)<90)&&(image_cr(i,j)>130&&image_cr(i,j)<140))
                    output_image3(i,j)=1;
                 
           end
           
           if((image_cb(i,j)>110&&image_cb(i,j)<120)&&(image_cr(i,j)>160&&image_cr(i,j)<175))
                        output_image4(i,j)=1;
        end
           
           if((image_cb(i,j)>120&&image_cb(i,j)<130)&&(image_cr(i,j)>140&&image_cr(i,j)<150))
                        output_image5(i,j)=1;
           end
           
           if((image_cb(i,j)>100&&image_cb(i,j)<110)&&(image_cr(i,j)>165&&image_cr(i,j)<175))
                        output_image6(i,j)=1;
           end
                    
               
                end
            end
                    
    red=sum(sum(output_image1));
    green=sum(sum(output_image2));
    blue=sum(sum(output_image3));
    yellow=sum(sum(output_image4));
    pink=sum(sum(output_image5));
    brown=sum(sum(output_image6));
    a=[red green blue yellow pink brown];
   
    max=0;
    for i=1:6
        if(a(i)>max)
            max=a(i);
            max1=i;
        end
    end
    if(max1==1)
        disp('red');
    end
    if(max1==2)
        disp('green');
    end
    if(max1==3)
        disp('blue');
    end
    if(max1==4)
        disp('yellow');
    end
    if(max1==5)
        disp('pink');
    end    
    if(max1==6)
        disp('brown');
    end

end

Comments