Tuesday, April 26, 2011

Color detecting

I got several requests to share the color detecting Matlab code.
To run this demo, you may need a webcam.
This code is based on YUY2 type of webcam.
So if you are using RGB type webcam, just remove "tmp = YUY2toRGB(tmp)" in the code.
Enjoy! :)

===================================================================

clear all;
close all;
frame=1;
images = [];

ImageBlur = 0.04 * ones(5,5);
H = fspecial('gaussian',[5 5],1.5);


%try
%% imaqreset;
if ~exist('vid')
vid = videoinput('winvideo', 1, 'YUY2_320x240');
preview(vid);
disp 'preview';
end
figure(1);
set(gcf, 'BackingStore', 'off');
figure(2);
set(gcf, 'toolbar', 'none');
set(gcf, 'MenuBar', 'none');
set(gcf, 'BackingStore', 'off');

while(1)
tmp=getsnapshot(vid);
tmp=YUY2toRGB(tmp);
images(:,:,:) = tmp;
if (size(images,3) >= 2)
set(0,'CurrentFigure',2)
imshow(tmp);
hold on;

temp_x=0;
temp_y=0;
n=0;
rad=0;
rad2=0;
for x = 1 :320;
for y = 1 : 240;
if (images(y,x,1)<20 && images(y,x,2)<20 && images(y,x,3)<20)
n=n+1;
temp_x=temp_x+x;
temp_y=temp_y+y;
rad=rad+1;
end;
end;
if(rad>rad2)
rad2=rad;
end;
rad=0;
end;
center_x=round(temp_x/n);
center_y=round(temp_y/n);
r=rad2/2;
t = 0:0.1:2*pi+0.2;
rx = center_x + r * cos(t); ry = center_y + r * sin(t); % circle drawing
line([center_x-10 center_x+10], [center_y center_y],'Color','c' ,'LineWidth',[2]);
line([center_x center_x], [center_y-10 center_y+10],'Color','c' ,'LineWidth',[2]);
line([160-10 160+10],[120 120],'Color','y' ,'LineWidth',[2]);
line([160 160],[120-10 120+10],'Color','y' ,'LineWidth',[2]);
plot(rx,ry,'c');
hold off;
drawnow;
end

%catch exception
% exception.getReport
%end
end

if exist('vid')
delete(vid);
clear vid;
end

No comments:

Post a Comment