2
$\begingroup$

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?

$\endgroup$

1 Answer 1

5
$\begingroup$

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

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

Mathematica graphics

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)}]}]

Mathematica graphics

$\endgroup$
3
  • $\begingroup$ Thank you very much, i'm a bit of a newbie to mathematica, so its much appriciated when people help out. $\endgroup$
    – Morphalog
    Nov 26, 2015 at 10:51
  • 1
    $\begingroup$ 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. $\endgroup$ Nov 26, 2015 at 11:15
  • 1
    $\begingroup$ Thanks for pointing that out. I got bitten by the different coordinate system too many times... $\endgroup$
    – shrx
    Nov 26, 2015 at 11:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.