labelme dataset, json to png format

The data set produced by labelme is in json file format, and python is used to convert batch json to png format.

This method converts png pixels to 0 and 1.

code show as below:

import os
import cv2
import numpy as np
from PIL import Image, ImageDraw
import json

CLASS_NAMES = ['Ice']


def make_mask(image_dir, save_dir):
    data = os.listdir(image_dir) # 文件列表
    temp_data = []
    for i in data:
        if i.split('.')[1] == 'json':
            temp_data.append(i) # 拿到所有的json文件
        else:
            continue
    for js in temp_data:
        json_data = json.load(open(os.path.join(image_dir, js), 'r')) # 'r'读的形式
        shapes_ = json_data['shapes']
        mask = Image.new('P', Image.open(os.path.join(image_dir, js.replace('json', 'png'))).size) # 'P'八位
        for shape_ in shapes_:
            label = shape_['label']
            points = shape_['points']
            points = tuple(tuple(i) for i in points) # 转元组
            mask_draw = ImageDraw.Draw(mask) # 可以对mask进行画图的操作
            mask_draw.polygon(points, fill=CLASS_NAMES.index(label) + 1) # 进行画多边形的操作
        mask.save(os.path.join(save_dir, js.replace('json', 'png')))


def vis_label(img):
    img=Image.open(img)
    img=np.array(img)
    print(set(img.reshape(-1).tolist()))



if __name__ == '__main__':
    image_dir=r"D:\1"
    save_dir=r"D:\out"

    # Json转Png
    make_mask(image_dir, save_dir)

    # vis_label('SegmentationClass/000799.png')

    # 读取某一张图并显示
    img=Image.open(r"D:\out\01.png") # 读取其中一张
    img=np.array(img)*255
    cv2.imshow("1",img)
    cv2.waitKey(0)
    print(np.array(img).shape)
    out=np.array(img).reshape(-1)
    print(set(out.tolist()))

Guess you like

Origin blog.csdn.net/weixin_52127098/article/details/124880088