使用 labelme 库中的 labelme_to_png 函数实现labelme json文件转换为png
时间: 2023-10-13 16:20:50 浏览: 228
labelme标注生成png
首先需要安装 labelme 库:
```
pip install labelme
```
然后可以使用以下代码将 labelme 的 json 文件转换为 png 文件:
```python
from labelme import utils
import json
import numpy as np
import cv2
def labelme_to_png(json_file, save_dir):
with open(json_file, 'r') as f:
data = json.load(f)
img = utils.img_b64_to_arr(data['imageData'])
label_name_to_value = {'_background_': 0}
for shape in sorted(data['shapes'], key=lambda x: x['label']):
label_name = shape['label']
if label_name in label_name_to_value:
label_value = label_name_to_value[label_name]
else:
label_value = len(label_name_to_value)
label_name_to_value[label_name] = label_value
lbl = np.zeros(img.shape[:2], dtype=np.int32)
for shape in data['shapes']:
label_name = shape['label']
label_value = label_name_to_value[label_name]
mask = utils.shape_to_mask(img.shape[:2], shape['points'], shape['shape_type'])
lbl[mask] = label_value
lbl_viz = utils.draw_label(lbl, img, label_name_to_value)
cv2.imwrite(save_dir, lbl_viz)
```
其中,`json_file` 是 labelme 的 json 文件路径,`save_dir` 是保存 png 文件的路径。经过上述代码处理后,会在 `save_dir` 目录下生成对应的 png 文件。
阅读全文