百度飞浆EasyDL深度学习图像检测或图像分割数据集导出后的数据集的标签格式默认是Json的,但是有些神经网络的模型是需要PNG标签的,尝试了一些方法后成功将json标签转成PNG了,yes
import json
import cv2
import numpy as np
import pycocotools.mask as mask_util
import os
input_folder = '.json' #替换为你的.json文件夹路径
output_folder = 'pngs' #替换为你准备存放的png文件夹路径
os.makedirs(output_folder, exist_ok=True)
colors = {
#选择你的标签轮廓想要的颜色,1和2为标签名,可以是单个或多个,更具你的标签信息更改,RGB颜色的色值可以参考我的另一篇博客。
"1": (233, 139, 0), #(B,G,R)
"2": (0, 165, 255) #(B,G,R)
}
for filename in os.listdir(input_folder):
if filename.endswith('.json'):
file_path = os.path.join(input_folder, filename)
# 读取JSON文件
with open(file_path, 'r') as file:
data = json.load(file)
# 创建一个空白图像
height, width = data['labels'][0]['size']['height'], data['labels'][0]['size']['width']
image = np.zeros((height, width, 3), dtype=np.uint8)
# 绘制轮廓线和文本
for label in data['labels']:
# 解码掩码
rle = {
'counts': label['mask'],
'size': [height, width]
}
mask = mask_util.decode(rle)
# 查找轮廓
contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 获取标签颜色
color = colors.get(label['name'], (255, 255, 255))
# 绘制轮廓线
cv2.drawContours(image, contours, -1, color, 2)
output_file = os.path.join(output_folder, f'{os.path.splitext(filename)[0]}.png')
cv2.imwrite(output_file, image)
print("All images have been processed and saved.")