# Finding pixel coordinates from morphological components

I used morphological components to find the connected components in a binary image, is there a way to find the pixel postions for these integers?

From the documentation of ComponentMeasurements, components' masks can be returned as sparse arrays.

testImage = Uncompress@Import["http://pastebin.com/raw.php?i=t8bUL5HH", "Text"]


imgPositions = #["NonzeroPositions"] & /@ ComponentMeasurements[testImage, "Mask"][[All, 2]]

{{{2, 4}, {2, 5}, {2, 6}, {3, 4}, {3, 6}, {4, 4}, {4, 5}, {4, 6}},
{{6, 2}},
{{6, 4}, {6, 5}, {6, 6}}}


To convert imgPositions from the image's coordinate system to the more intuitive coordinates used by Graphics, etc., you can use:

y = ImageDimensions[testImage][[2]];
coordinates = Map[{-1, y} + Reverse[#]*{1, -1} &, imgPositions, {2}]

{{{3, 5}, {4, 5}, {5, 5}, {3, 4}, {5, 4}, {3, 3}, {4, 3}, {5, 3}},
{{1, 1}},
{{3, 1}, {4, 1}, {5, 1}}}

Show[{Show[testImage, ImageSize -> 50], Graphics[{Red, Point /@ (coordinates + .5)}]}]


• Thank you very much, i'm a bit of a newbie to mathematica, so its much appriciated when people help out. Nov 26, 2015 at 10:51
• Except that those aren't coordinates, they're array indices. Indices start at the top-left corner, which is 1/1, and the first index is the row (y-direction). Coordinates start at the bottom-left corner, which is 0/0, and the first coordinate is the x-direction. If you need coordinates, and you don't want to do the error-prone conversion yourself, the easiest way is probably PixelValuePositions[Image[#], 1]& - might be slower, though. Nov 26, 2015 at 11:15
• Thanks for pointing that out. I got bitten by the different coordinate system too many times...
– shrx
Nov 26, 2015 at 11:28