Can't detect yellow colour using hsv method.

2 views (last 30 days)
Aliff
Aliff on 18 Sep 2012
I've put together some codes that I found here so that it will function as I desire. I want the code to detect yellow colour using hsv method and draw a bound box around the yellow object. I've managed to get the code started but it won't detect the yellow colour or any other colour (I printed out a wheel of colour on paper and use it to test the code).
close all
clear all
clc
vid=videoinput('winvideo',1,'YUY2_160x120');
set(vid,'TriggerRepeat',Inf);
vid.returnedcolorspace='rgb';
vid.FrameGrabInterval=2;
start(vid)
while(vid.FramesAcquired<=200)
data1=getdata(vid,1);
hsvFrame = rgb2hsv( data1 );
%sets all values for pixels that are not within the yellow range to zero.
hsvFrame( hsvFrame( : , : , 1 ) > 0.2 ) = 0;
hsvFrame( hsvFrame(: , : , 3) < 0.25 ) = 0;
diff_m = find( hsvFrame( : , : , 1 ) ~=0 );
bw= bwlabel(diff_m,8);
stats=regionprops(bw,'BoundingBox','Centroid');
imshow(data1)
hold on
for object=1:length(stats)
bb=stats(object).BoundingBox;
bc=stats(object).Centroid;
rectangle('Position',bb,'EdgeColor','Y','LineWidth',2);
plot(bc(1),bc(2),'-m+');
a=text(bc(1)+15,bc(2),strcat('X:',num2str(round(bc(1))),'Y:', num2str(round(bc(2)))));
set(a,'FontName','Arial','FontWeight','bold','FontSize',12,'Color','yellow');
end
hold off
end
stop(vid)
flushdata(vid);
clear all
Also if I set my camera resolution more than 160x120, it will cause some lag

Answers (2)

Jan
Jan on 18 Sep 2012
Are you sure you want this:
hsvFrame( hsvFrame(: , : , 1) > 0.2 ) = 0;
hsvFrame( hsvFrame(: , : , 3) < 0.25 ) = 0;
Or should the 2nd line concern the 1st slice also?
What do you expect as output of the above commands? hsvFrame(: , : , 3) < 0.25 is a 2D logical array, while hsvFrame is 3D. Therefore you process the first slice only in both lines.
Using IMSHOW repeatedly is much slower than showing the image ones and updateing the CData property afterwards.
  3 Comments
Jan
Jan on 18 Sep 2012
Edited: Jan on 18 Sep 2012
About CData:
imageH = imshow(rand(200, 200, 3));
drawnow;
% Slow:
imshow(rand(200, 200, 3));
% Fast:
set(imageH, 'CData', rand(200, 200, 3));
"hsvFrame(:,:,3) < 1" is strange. The V value is limited to 1 in every case.
Aliff
Aliff on 19 Sep 2012
Edited: Aliff on 19 Sep 2012
Ok, i've tried using the CData, but I don't know if this the correct way to use it here:
data1 = imshow(rand(120, 160, 3));
drawnow;
I've ran the code and all i get is random noises in the image.

Sign in to comment.


Jan
Jan on 18 Sep 2012
bwlabel operates on binary 2D images. So do not use
diff_m = find( hsvFrame( : , : , 1 ) ~=0 ); % BAD here
bw = bwlabel(diff_m,8)
but:
diff_m = hsvFrame( : , : , 1 ) ~=0;
bw = bwlabel(diff_m,8)

Categories

Find more on Convert Image Type in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!