0

Can not make binary mask from self-intersected polygon.

import numpy as np
from PIL import Image, ImageDraw


def show(img,full=False):
    if full:
        display(Image.fromarray(np.uint8(img)))
    else:
        img = resize(img,300)
        display(img)

def polygons_to_mask(poly,shape):

    def points_to_float(point_str):
        a= point_str.split(",")
        # print(a)
        return (int(float(a[0])),int(float(a[1])))

    points = [ points_to_float(x) for x in poly.split(";")]
    points1d = []
    for p in points:
        points1d +=p 
    img = Image.new("L", [shape[0], shape[1]], 0)
    ImageDraw.Draw(img).polygon(points1d, outline=1, fill=1)
    mask = np.array(img)
    return mask


def points_to_float(point_str):
        a= point_str.split(",")
        # print(a)
        return (int(float(a[0])),int(float(a[1])))


poly = "30,20;30,60;60,60;60,30;20,30;20,40;50,40;50,50;40,50;40,20"

mask = polygons_to_mask(poly,(80,80))



# print(mask)
show(mask*255)

current result mask is: https://i.stack.imgur.com/LalaF.png

but I need like that: https://i.stack.imgur.com/XeHQP.png

tried PIL draw polygon and this polygon2mask . the result is the same.

Boris G
  • 1
  • 1
  • 1
    Why not just break your polygon into 2 (or more) convex polygons? Self-intersecting and concave polygons can present many inconvenient edge cases and the typical fix is to break the polygon down (commonly into triangles) rather than deal with the issues on the algorithm side. – Woodford Feb 23 '23 at 16:35
  • yet do not understand how to do that in an elegant way (or even any way :) ) – Boris G Feb 23 '23 at 17:19
  • I don't do much of this sort of thing, but you may have more luck making it into an SVG and then go from there to a PNG. – Mark Setchell Feb 23 '23 at 20:12
  • I'll try just to check that. But I think it isn't the solution – Boris G Feb 24 '23 at 09:20

0 Answers0