Generating Masks from Polygon

Sample Script

Use this sample script as a base to generate your polygon masks from a polygon instance list from a diffgram export:

This is a contribution from a community member

instance_list = [{'points': [{'x': 10, 'y': 10}, {'x': 20, 'y': 20}, {'x': 30, 'y': 30}]}]
points_local = []
for i, polygon in enumerate(instance_list):

    for point in polygon['points']:
        points_local.append((point['x'], point['y']))


    background = Image.new('L', (image.width, image.height), 0)
    if len(points_local) >= 2:
        ImageDraw.Draw(background).polygon(points_local, outline = 255, fill = 255)
    background = np.array(background)

    file_name = f"{self.temp}/{str(i)}.png"

    # Could do 0 index thing but this preserves which polygon it'session referring to... not sure

    mask_blob_name = "my_mask.png"

    imwrite(file_name, background.astype(np.uint8))

Did this page help you?