MATLAB: Finding objects in images

image processing

I am trying to find only spherical objects like ball … I wrote a code to track the "orange" colored ball but it is not showing anything so please tell me the mistake…….and also how to track object of different shape with with different colors..
vid=videoinput('winvideo',2,'I420_320x240');
set(vid,'FramesPerTrigger',Inf);
set(vid,'ReturnedColorspace','rgb');
vid.FrameGrabInterval=2;
framesneeded=300;
start(vid)
while(vid.FramesAcquired<=framesneeded)
RGB=getsnapshot(vid);
R=RGB(:,:,1);
R=fliplr(R);
G=RGB(:,:,2);
G=fliplr(G);
B=RGB(:,:,3);
B=fliplr(B);
RGB=cat(3,R,G,B);
R=((R+G))-(B);
bw=R>60;
bw=medfilt2(bw,[3 3]);
bw=bwareaopen(bw,20);
bw=bwconncomp(bw,8);
stats=regionprops(bw,'CENTROID','Eccentricity');
imshow(RGB)
hold on
if length(stats)>1
ecc= stats(1).Eccentricity;
if(ecc<0.2)
cent=stats(1).Centroid;
plot(cent(1),cent(2),'+','MarkerfaceColor','g','markerSize',30);
end
end
hold off
flushdata(vid);
end

Best Answer

The problem is most likely here:
R=((R+G))-(B);
Since R and G are probably uint8, when you add them, they probably go past 255 and so the result is clipped. Cast to single or uint16 before adding. To get the difference between the average of the red and green channel, and the blue channel, do this:
averageDifferenceImage = (single(R) + single(G))/2 - single(B);
At that point, you can cast it back into uint8 if you want:
averageDifferenceImage = uint8(averageDifferenceImage);
Also, Eccentricity is not good for finding circles. I think squares would even have the same eccentricity as circles. It's better to use the circularity, which unfortunately is not built in to regionprops() yet. But you can do this
stats=regionprops(bw,'Area','Perimeter');
circularities = ([stats.Perimeter] .^ 2) ./ (4 * pi * [stats.Area]);
Circularity will be 1 for perfect circles and gets higher the more non-circular the blob gets.
Related Question