本实例代码主要使用labelme.utils.shapes_to_label方法实现批量将将labelme的语义分割标注数据转换为图片,支持将标注保存为实例分割训练图、语义分割训练图、语义分割+原图效果叠加图。
1、用labelme进行语义分割标注标注软件可以到这里下载
labelme-4.5.7.exe_labelme-深度学习文档类资源-CSDN下载
2、得到系列标注文件 3、运行代码将标注文件保存为图片其中的label_name_to_value 数组需要自行设置和修改,
'_background_': 0,没有标注的地方为算法默认背景区域
import json
import os
import warnings
warnings.filterwarnings('ignore')#屏蔽不需要的错误警告
from labelme import utils
import numpy as np
from skimage import io
from PIL import Image
def draw_json_file(json_dir=""):
json_files=glob.glob(os.path.join(json_dir, '*.json'))
label_name_to_value = {'_background_': 0, "background": 1, "vehicle": 2}
#最多支持21种颜色
colors = [(0, 0, 0), (128, 0, 0), (0, 128, 0), (128, 128, 0), (0, 0, 128), (128, 0, 128), (0, 128, 128),
(128, 128, 128), (64, 0, 0), (192, 0, 0), (64, 128, 0), (192, 128, 0), (64, 0, 128), (192, 0, 128),
(64, 128, 128), (192, 128, 128), (0, 64, 0), (128, 64, 0), (0, 192, 0), (128, 192, 0), (0, 64, 128),
(128, 64, 12)]
for path in json_files:
data = json.load(open(path))
img = io.imread(json_dir+data['imagePath'])
#lbl:语义分割label图 ins:实例分割label图
lbl, ins = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)
#生产彩色分割图
seg_img = np.zeros((img.shape[0],img.shape[1], 3),np.uint8)
for c in range(len(label_name_to_value)):
seg_img[:,:,0] += ((lbl[:,: ] == c )*( colors[c][0] )).astype('uint8')
seg_img[:,:,1] += ((lbl[:,: ] == c )*( colors[c][1] )).astype('uint8')
seg_img[:,:,2] += ((lbl[:,: ] == c )*( colors[c][2] )).astype('uint8')
#将彩色分割图与原图进行混合
seg_img = Image.blend(Image.fromarray(img),Image.fromarray(seg_img), 0.7)
#保存彩色分割图
seg_img.save(path.replace(".json",'_color_label.png'))
#将具体的语义分割label值保存为文件
Image.fromarray(lbl).save(path.replace(".json",'_lbl.png'))
#将具体的实例分割label值保存为文件
Image.fromarray(ins).save(path.replace(".json",'_ins.png'))
#保存放大label到255的label图
io.imsave(path.replace(".json",'语义分割.png'),lbl,check_contrast=False)
io.imsave(path.replace(".json",'实例分割.png'),ins,check_contrast=False)
print(path)
if __name__ == '__main__':
draw_json_file(r"C:UsersAdministratorDesktop数据\")
运行得到的结果如下图所示
其中后缀为_ins.png的数据表示用于实例分割,后缀为_lbl.png的数据表示用于语义分割



