# Calculate the centroid of a group of pixels with the same PixelValuePositions

My question is about how to recognise objects in a image. I would like to recognise objects of the same color. Then I want to calculate the centroid of these objects. I want to apply this calculation on the image below.

Based on the centroid it is possibe to calculate the xy-coordinate of the soccer players on this field. The difficulty is that the soccer players can wear a shirt and socks of the same color, but I will be happy if I can get an approximation.

-
Do you know the colors in advance? – Dr. belisarius Feb 20 '14 at 21:42
Another difficulty is that you will have to eliminate the signage in the background which is close to the colors you want pick out. – m_goldberg Feb 20 '14 at 23:41

Here's a way to approach this using the image processing tools. The strategy is to pick out all the "red" points and then build an image that is "1" where the original is red and "0" elsewhere. This image is then dilated to join disconnected points into small regions, and then ComponentMeasurements can pick out the centroids of the regions.

img = Import["http://i.stack.imgur.com/xNI6h.gif"];
red = PixelValuePositions[img, Red, 0.3];
{h, v} = ImageDimensions[img];
imgD = ConstantArray[0, {h, v}];
Table[imgD[[Sequence @@ red[[i]]]] = 1, {i, 1, Length[red]}];
redPeople = ImageRotate[Dilation[Image[imgD], 8], Pi/2]
ComponentMeasurements[redPeople, "Centroid"]


{1 -> {245.5, 282.5}, 2 -> {269.5, 282.5}, 3 -> {303.122, 264.764},
4 -> {527.932, 256.638}, 5 -> {176.523, 251.484},
6 -> {63.8244, 244.554}, 7 -> {398.713, 160.209}}


As you can see, this procedure has located 7 red players which is, hopefully, close enough to make the OP happy! A procedure for the blue players would proceed in the same manner.

To see what is happening: imgD is initialized as an array of all zeros. The Table is basically like a Do loop that sets all of the red points (saved in the variable red) to 1. When indexing into imgD, the indices need to be of the form imgD[[x,y]] and if we use imgD[[{x,y}]] it will fail. So the Sequence command strips the outer braces { } from the values in red.

-
Hi Bill, This is a very good solution. Thank you very much. Can you explain what happens when you write: imgD = ConstantArray[0, {h, v}]; Table[imgD[[Sequence @@ red[[i]]]] = 1, {i, 1, Length[red]}]; – Michiel van Mens Feb 21 '14 at 15:27
Hi Michiel van Mens -- I have updated the answer to more fully describe how the procedure works. – bill s Feb 21 '14 at 16:18