Calculate if intersection between polygon and raster image
-
10-12-2019 - |
Question
If I have an binary image and a irregular convex polygon how can I calculate if they intersect each other? The coordinates of the polygon are described in terms of the image.
I have a few ideas on this, coming from either a collision detection or fill algorithm perspective, but I don't think either would be optimal. I'm sure there is a tried and tested method for this but can't think of the keywords.
Here is an example of what I mean:
In this case it should return true.
Solution
I would recommend this following algorithm:
Traverse the border of the polygon using Bresenham's algorithm for each line, and at each pixel, sample the raster. If it's a color you accept to be visible, such as a nonzero alpha, report an intersection.
This has the advantage of only working over the edges of the polygon, so you don't need to iterate over all the pixels inside the polygon.