Read Labelme annotations in Python
Unofficial preview. Docsbook assembled this page from the public
wkentaro/labelmeREADME.mdandexamples/directory. It is not affiliated with, endorsed by, or maintained by the Labelme project. The official documentation lives at labelme.io/docs.
Labelme has no public Python API. It is an application, and since v7 its internal modules are underscore-prefixed, so import labelme.utils no longer works. The supported way to consume its output from your own code is to read the JSON format directly — the way a PyTorch Dataset reads whatever format its data happens to live in.
Start from examples/utils.py#
The repository ships examples/utils.py as the worked reference for exactly this. It depends only on the standard library, numpy and PIL, never on Labelme itself, so it keeps working regardless of how Labelme's internals change. It re-implements the rasterisation helpers rather than importing them, deliberately: that copy and Labelme's internal copy have different owners and lifecycles.
Copy the file next to your own scripts and adapt it.
What loading a label file involves#
The file gives you the shapes and the image bytes. Two details decide whether your loader works on somebody else's annotations:
- The image may or may not be inside the JSON. When
imageDatais present it is base64-encoded image bytes. When it is absent, resolveimagePathrelative to the JSON file's own directory. imagePathmay be a Windows path. An annotation made on Windows can carry backslashes.examples/utils.pynormalises it throughPureWindowsPath(...).as_posix()before joining, which is why the same dataset opens on Linux.
Each shape it returns carries label, points, shape_type, group_id, flags and an optional decoded mask. Shapes with no shape_type default to polygon.
Loading a label PNG#
Label PNGs written by the export scripts hold class indices, not brightnesses. Open them with PIL.Image.open — scipy.misc.imread and skimage.io.imread may not return the values correctly:
import numpy as np
import PIL.Image
lbl = np.asarray(PIL.Image.open("apc2016_obj3/label.png"))
print(lbl.dtype) # uint8
print(np.unique(lbl)) # [0 1 2 3]
print(lbl.shape) # (907, 1210)The values are low on purpose. 255 marks the __ignore__ label, which is -1 in the matching npy file.
If you must keep the old imports#
Pin the previous major line and vendor the code you need:
pip install 'labelme<7'All previous releases remain installable from PyPI. This is a way to buy time, not a supported long-term interface — see upgrading to v7.
Related#
- Annotation JSON reference — every field you will parse
- Export to COCO — when a standard format beats a custom loader
- Upgrade to v7