Set Shape Flag defaults in Settingsv7.6.0

Export a polygon mask to PNG

Create a class-label mask from the polygon example. This Python exercise supports polygons only. For dataset conversion to training formats, see the Pro toolkit documentation.

Prepare the annotation

Put dogs.json and dogs.jpg in the same folder. Install Pillow:

python -m pip install pillow

Export the mask

Save this as export_annotated.py beside the sample files:

import json
from pathlib import Path

from PIL import Image, ImageDraw

annotation = json.loads(Path("dogs.json").read_text())
shapes = annotation["shapes"]
if any(shape["shape_type"] != "polygon" for shape in shapes):
    raise ValueError("This example exports polygons only.")

labels = sorted({shape["label"] for shape in shapes})
if len(labels) > 255:
    raise ValueError("This example supports at most 255 labels.")

mask = Image.new("L", (annotation["imageWidth"], annotation["imageHeight"]), 0)
draw = ImageDraw.Draw(mask)
for shape in shapes:
    label_id = labels.index(shape["label"]) + 1
    draw.polygon([tuple(point) for point in shape["points"]], fill=label_id)

output = Path("dogs_exported")
output.mkdir(exist_ok=True)
mask.save(output / "label.png")
(output / "label_names.json").write_text(json.dumps(["_background_", *labels]))
print("Created", output / "label.png")

Run it:

python export_annotated.py

You should get a dogs_exported folder containing label.png and label_names.json. Background pixels have value 0 and dog pixels have value 1. The mask will look almost black in an image viewer because 1 is close to 0; it is data, not a colored preview. Later polygons overwrite earlier ones where they overlap.

Running the script again overwrites those two files. Use a separate folder if you need to keep an earlier export.

Check the result

Continue with Read an exported mask to inspect its pixel values and see a black-and-white preview. You can also download the example export.