提出问题
研究中经常利用labelme等标注软件进行标注,但对于这些软件保存的json文件(以坐标形式保存的)如何转换成mask存在麻烦。网上的帖子给出的方法是改labelm配置文件等,也试过,但每次修改存在麻烦,因此,自己改进了一些代码,可以迅速转换.json->mask的图片表示。具体的转换过程如下图,即将原图和json文件混合的文件夹转化成两个文件夹,一个存放原图,一个存放标签。

解决方法
import cv2
import numpy as np
import json
import glob
import os
category_types = ["Background", "IP", "CRSwNP", "normal"]
for i in glob.glob('./data/*.jpg'):
    name = os.path.split(i)[-1][:-4]
    print (name)
    img = cv2.imread(i)
    h, w = img.shape[:2]
    mask = np.zeros([h, w, 3], np.uint8)    # 创建一个大小和原图相同的空白图像
    #mask = np.zeros([h, w, 3], np.uint8) #单通道
    with open("./data/{}.json".format(name), "r") as f:
        label = json.load(f)
    shapes = label["shapes"]
    for shape in shapes:
        category = shape["label"]
        points = shape["points"]
        # 填充
        points_array = np.array(points, dtype=np.int32)
        if category_types.index(category) == 1:
            mask = cv2.fillPoly(mask, [points_array], (0, 255, 0))
        elif category_types.index(category) ==2:    
            mask = cv2.fillPoly(mask, [points_array], (0, 0, 255))
        elif category_types.index(category) == 3:    
            mask = cv2.fillPoly(mask, [points_array], (255, 0, 0))
        else:
            mask = cv2.fillPoly(mask, [points_array], (0, 0, 0))
    #mask = cv2.fillPoly(mask, [points_array], category_types.index(category))##单通道
    cv2.imwrite("./datasets/masks/{}.png".format(name), mask)
    cv2.imwrite("./datasets/images/{}.png".format(name), img)

 
                
文章评论