Find an object in an image by color

So I'm using a webcam to take a color picture of an area. In that area there is a red thing and a green thing among a bunch of other things. Basically I need to return the location of the center of the red thing and the green thing. The exact shape of the objects is not known in advance.
Basically I just need to tell matlab to find the color thing and have it give me coordinates from a color image

 Accepted Answer

See my attached demo where I track a green thing in the video. It's a simple matter to add a check for red things.

3 Comments

Morpheuskibbe
Morpheuskibbe on 17 Apr 2017
Edited: Morpheuskibbe on 17 Apr 2017
Ok lets see if im following. A lot of this is displaying stuff for your demo and hence unnecessary for me so I'm just parsing whats needed and whats not.
Given RGB image "img" I THINK this is all i need from your code.
hThresholds = whatever
sThresholds = whatever
vThresholds = whatever
hsv = rgb2hsv(double(img));
hue=hsv(:,:,1);
sat=hsv(:,:,2);
val=hsv(:,:,3);
binaryH = hue >= hThresholds(1) & hue <= hThresholds(2);
binaryS = sat >= sThresholds(1) & sat <= sThresholds(2);
binaryV = val >= vThresholds(1) & val <= vThresholds(2);
coloredMask = binaryH & binaryS & binaryV;
coloredMask = bwareaopen(coloredMask, 500);
coloredMask = imfill(coloredMask, 'holes');
[labeledImage, numberOfRegions] = bwlabel(coloredMask);
stats = regionprops(labeledImage, 'BoundingBox', 'Centroid');
And then stats(r).Centroid would be an array of coordinates for the centers of detected things of the desired color? Do I have this right?
stats(r).Centroid would be a 1 by 2 array with the (x,y) coordinate of the r'th centroid. To get all centroids, for all blobs, do
centroids = [stats.Centroid];
xCentroids = centroids(1:2:end);
yCentroids = centroids(2:2:end);
Thanks. It works. I changed it a bit
the line: " hsv = rgb2hsv(double(img));" I just changed to "hsv = rgb2hsv(img);"
I noticed that if I did it that way then the V value was limited to the range 0-1 just like the others instead of big numbers like in your example

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!