Created
July 7, 2021 17:23
-
-
Save afrendeiro/21a510caa6cec41a2ec51d571966ee57 to your computer and use it in GitHub Desktop.
Convert a labeled image mask to a JSON file compatible with labelme. Useful to export predictions and then fine tune by hand with labelme.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(): | |
return | |
polygons = Mask(labeled_image).polygons() | |
shapes = list() | |
for point in polygons.points: | |
if not simplify: | |
poly = np.asarray(point).tolist() | |
else: | |
poly = np.asarray( | |
Polygon(point).simplify(simplification_threshold).exterior.coords.xy | |
).T.tolist() | |
shape = { | |
"label": "A", | |
"points": poly, | |
"group_id": None, | |
"shape_type": "polygon", | |
"flags": {}, | |
} | |
shapes.append(shape) | |
f = io.BytesIO() | |
imageio.imwrite(f, tifffile.imread(filename), format="PNG") | |
f.seek(0) | |
encoded = base64.encodebytes(f.read()) | |
payload = { | |
"version": "4.5.6", | |
"flags": {}, | |
"shapes": shapes, | |
"imagePath": filename.name, | |
"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