Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Convert a labeled image mask to a JSON file compatible with labelme. Useful to export predictions and then fine tune by hand with labelme.
import pathlib
import numpy as np
def mask_to_labelme(
labeled_image: np.ndarray,
filename: pathlib.Path,
overwrite: bool = False,
simplify: bool = True,
simplification_threshold: float = 5.0,
) -> None:
import io
import base64
import json
import imageio
from imantics import Mask
from shapely.geometry import Polygon
output_file = filename.replace_(".tif", ".json")
if overwrite or output_file.exists():
polygons = Mask(labeled_image).polygons()
shapes = list()
for point in polygons.points:
if not simplify:
poly = np.asarray(point).tolist()
poly = np.asarray(
shape = {
"label": "A",
"points": poly,
"group_id": None,
"shape_type": "polygon",
"flags": {},
f = io.BytesIO()
imageio.imwrite(f, tifffile.imread(filename), format="PNG")
encoded = base64.encodebytes(
payload = {
"version": "4.5.6",
"flags": {},
"shapes": shapes,
"imageData": encoded.decode("ascii"),
"imageHeight": labeled_image.shape[0],
"imageWidth": labeled_image.shape[1],
with open(output_file.as_posix(), "w") as fp:
json.dump(payload, fp, indent=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment