Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ComponentMeasurements[ _ ,"Centroid"] results offset

I need to get the Center of Mass (Centroid) for components in a set of binary images with subpixel accuracy.

Mathematica 8 comes with a nice addition:

i =  Import@"http://i.stack.imgur.com/2pxrN.png";  
m1 = ComponentMeasurements[MorphologicalComponents[i], "Centroid"] /. 
                                                                Rule[_, x_] -> x
(*
-> {{403.229, 453.551}, {660.404, 371.383}, {114.389, 434.646}, {295.5, 206.}}
*)

But I went through some troubles when those results showed some inconsistencies with other calculations done elsewhere.

So I rolled my own, perhaps not nice:

i = Import@"http://i.stack.imgur.com/2pxrN.png";
f[i_] := N@{#[[2]], ImageDimensions[i][[2]] - #[[1]]} & /@
         ( Mean /@
             Function[x, Map[
                Position[x, #, 2] &,
                Complement[Union@Flatten[x], {0}]]]
             [MorphologicalComponents[i]]);
f[i]
Show[i, Graphics[{Red, Disk[#, 10] & /@ f[i]}]]
(*
-> {{403.729, 453.051}, {660.904, 370.883}, {114.889, 434.146}, {296., 205.5}}
*)

enter image description here

You can see that there is a .5 offset between these results:

Thread[Subtract[m1, f[i]]]
(*
-> {{-0.5, -0.5, -0.5, -0.5}, {0.5, 0.5, 0.5, 0.5}}
*)

At first I thought that the problem was related with the image dimensions being even or odd, but that is not the case.

I'd prefer using ComponentMeasurements[ ..,"Centroid"] and correcting the results, but I'm afraid future Mma versions may modify this behavior and spoil the results.

I could also run a previous "calibration" with a known image and calculate the offsets, so it will auto-correct, but I would like to understand what is going on first.

Is this a bug?
Any ideas about why is this happening?

like image 678
Dr. belisarius Avatar asked Jun 24 '11 16:06

Dr. belisarius


1 Answers

I feel the doc page for ComponentMeasurements contains the solution:

Position, area, and length measurements are taken in the standard image coordinate system where position {0,0} corresponds to the bottom-left corner, x runs from 0 to width, and y runs from 0 to height.

You are counting whole pixels and ComponentMeasurements measures pixel positions. In this system, the center of the bottom left pixel is at {1/2,1/2}.

like image 122
Sjoerd C. de Vries Avatar answered Sep 17 '22 02:09

Sjoerd C. de Vries