在做一些异常检测模型任务时,需要批量把labelme生成的json文件转换成png图片,在这里把代码共享出来,大家可以需要时就可以拿来用哦!
代码如下:
import base64
import json
import os
import os.path as osp
import numpy as np
import PIL.Image
from labelme import utils
if __name__ == '__main__':
jpgs_path = "d:/XYF-code/work/GeneralAD-master/data/mydata/screen/test/NG" #图片所在路径
pngs_path = "d:/XYF-code/work/GeneralAD-master/data/mydata/screen/ground_truth/NG"#输出的结果保存路径
classes = ["_background_", "NG"]
count = os.listdir("d:/XYF-code/work/GeneralAD-master/data/mydata/screen/ground_truth/1") #(原图+labelme标注生成的.json文件)的路径
for i in range(len(count)):
path = os.path.join("d:/XYF-code/work/GeneralAD-master/data/mydata/screen/ground_truth/1", count[i])
if os.path.isfile(path) and path.endswith('json'):
data = json.load(open(path))
if data['imageData']:
imageData = data['imageData']
else:
imagePath = os.path.join(os.path.dirname(path), data['imagePath'])
with open(imagePath, 'rb') as f:
imageData = f.read()
imageData = base64.b64encode(imageData).decode('utf-8')
img = utils.img_b64_to_arr(imageData)
label_name_to_value = {'_background_': 0}
for shape in data['shapes']:
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
# label_values must be dense
label_values, label_names = [], []
for ln, lv in sorted(label_name_to_value.items(), key=lambda x: x[1]):
label_values.append(lv)
label_names.append(ln)
assert label_values == list(range(len(label_values)))
lbl = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)
lbl = lbl[0] # Assume lbl is a 2D array after shapes_to_label
PIL.Image.fromarray(img).save(osp.join(jpgs_path, count[i].split(".")[0] + '.jpg'))
# Create new array where the foreground will be white
new = np.zeros([lbl.shape[0], lbl.shape[1]], dtype=np.uint8)
for name in label_names:
index_json = label_names.index(name)
index_all = classes.index(name)
if index_all > 0: # Skip the background
new[lbl == index_json] = 255
# Save the PNG file using PIL.Image
new_image = PIL.Image.fromarray(new)
new_image.save(osp.join(pngs_path, count[i].split(".")[0] + '.png'))
print('Saved ' + count[i].split(".")[0] + '.jpg and ' + count[i].split(".")[0] + '.png')
结果展示:
要是对大家有帮助,我就很开心!!!!!