最近做计算机视觉相关工作,采用VIA工具进行标注,现在需要将其转为Labelme格式。
python
import json
import cv2
import os
import numpy as np
'''
0 正常
1 异常
2 有
3 无
'''
# 读取json文件
with open('01725bff-0fc6-4017-ad33-830df526438a.json', 'r', encoding='utf-8') as f:
data = json.load(f)
attribute = data['attribute']
file = data['file']
metadata = data['metadata']
label_data = {}
for key, value in metadata.items():
file_id = key.split('_')[0]
fname = file[file_id]['fname']
if fname not in label_data.keys():
label_data[fname] = []
xy_class = value['xy'][0]
xy_coords = value['xy'][1:]
av = value['av']['1']
if av == "0":
av = 2
if av == "1":
av = 3
if av == "2":
av = 0
if av == "3":
av = 1
if xy_class == 7:
label_data[fname].append((xy_coords, av))
# 以上是获取via标注的数据,下面是转换为labelme格式的json文件
with open('template.json', 'r', encoding='utf-8') as f:
template = json.load(f)
template['shapes'] = []
for f_n, d in label_data.items():
f_n = f_n.replace('http://192.168.122.111:8099/images/bo_pian', '.')
# f_w = open(f_n.replace('.jpg', '.txt'), 'w', encoding='utf-8')
json_w = f_n.replace('.jpg', '.json')
f_name = os.path.basename(f_n)
template['imagePath'] = f_name
img = cv2.imread(f_n)
# 获取图片的宽高
height, width, _ = img.shape
template['imageHeight'] = height
template['imageWidth'] = width
shapes = []
for coords, av in d:
shape = {
"label": str(av),
"text": "",
"points": np.array(coords).reshape(-1, 2).tolist(),
"group_id": None,
"shape_type": "polygon",
"flags": {}
}
shapes.append(shape)
template['shapes'] = shapes
# 将json数据写入文件
with open(json_w, 'w', encoding='utf-8') as f:
json.dump(template, f, ensure_ascii=False, indent=4)