I have a list of morphological components $m$, a set of vertices for a polytope $P$ (at real number coordinates), and I'd like to be able to calculate a list of morphological components $m'$ that anywhere overlap the area of $P$. I can do this by approximating each pixel as a point, and calculating a winding number for these points with respect to $P$ to determine if they fall within the polygon's area. However, this is hardly an efficient strategy, and it's not as exact as I would like. My hope is to have a scheme to detect if the polygon crosses any square bright pixel region. Is there a clever way to do this that works very quickly?


1 Answer 1


I suspect the quickest approach will be to rasterize the polygon. For example

Create an example component matrix:

m = MorphologicalComponents[ColorNegate@
    Rasterize[Graphics[Disk /@ RandomReal[{0, 20}, {40, 2}]], ImageSize -> {300, 300}]];

m // Colorize

enter image description here

Define the polygon and rasterize it:

poly = Polygon[{{50, 50}, {50, 250}, {200, 200}}];
polyimage = Binarize @ Graphics[poly, PlotRange -> {{0, 300}, {0, 300}}, ImageSize -> 300]

enter image description here

Identify values in m which overlap with zeros in polyimage (excluding the background component)

overlaps = Complement[Flatten @ Pick[m, ImageData[polyimage], 0], {0}]
(* {6, 7, 9, 13, 15, 19} *)

Check that the identified components do indeed overlap the polygon:

 SelectComponents[m, "Label", MemberQ[overlaps, #] &] // Colorize, {polyimage, 0.3}]

enter image description here


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.