Converting region of interest (ROI) polygon to a mask

I’d like to share a simple piece of code for converting a region of interest given by vertices of a polygon to a binary mask in Julia. This turned out to be more difficult than I expected so someone else may find this useful. I want to thank @cormullion for help and a really great library (Luxor.jl) that I used.

So, here is my code:

using Luxor
using Images
using ImageView

w = 512
h = 512
buffer = zeros(UInt32, w, h)
@imagematrix! buffer begin
    randompoints = [Luxor.Point(1.0, 1.0), Luxor.Point(10.0, 50.0), Luxor.Point(100.0, 25.0)]
    sethue("white")
    poly(randompoints, :fill)
end 512 512

rgb_buffer = map(p -> reinterpret(Images.RGB24, p), buffer)
my_mask = Gray.(rgb_buffer) .> 0.5
imshow(my_mask)

You just need to change randompoints to your sequence of vertices and change the size if needed and that’s it :slightly_smiling_face: . Let me know if there is a better way to do this.

3 Likes

I tried this way:


using Images
using GeometricalPredicates

pts = [(1.0, 1.0), (10.0, 50.0), (100.0, 25.0)]
adj = 256
randompoints = [Point(p[1] + adj, p[2] + adj) for p in pts]

w = 512
h = 512
buffer = zeros(Int, w, h)
poly = Polygon(randompoints...)
[if inpolygon(poly, Point(x, y)) buffer[x, y] = 1 end for x in collect(1:1:w), y in collect(1:1:h)];

then doing

Gray.(buffer)

should come up with a triangle.

3 Likes