import os
import json
import numpy as np
from labelme import utils
from skimage import img_as_ubyte
import matplotlib.pyplot as plt
path = './data_json/benign/00303466.json'
data = json.load(open(path))
imageData = data.get('imageData')
img = utils.img_b64_to_arr(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, _ = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)
mask = img_as_ubyte(lbl)
mask = np.uint8(mask) * 255 # 掩码
plt.subplot(1,2,1)
plt.imshow(img)
plt.axis('off')
plt.subplot(1,2,2)
plt.imshow(mask, 'gray')
plt.axis('off')
json文件加载后,是一个字典形式,其中存储了原始图像、图像名,图像高与宽、还有掩码的类别与坐标点
shapes中为掩码的信息,包括类别名与坐标点
结果:原图与mask