import os
from pathlib import Path
from tqdm import tqdm
import json
import numpy as np

def convert_2(size, box):
	w = (box[1] - box[0]) / size[0]
	h = (box[3] - box[2]) / size[1]
	x = (box[0] - box[1]) / 2 / size[0]
	y = (box[2] - box[3]) / 2 / size[1]
	return (x,y,w,h)

#yolov8姿态估计数据集json转txt脚本,假设json文件都在demo3/wrong中,需要把txt输出到wrongout路径中,框的名字叫roi
dir = 'demo3/wrong'
jsons = list(Path(dir).glob('*.json'))
for j in tqdm(jsons):
	with open(str(j), 'r') as f:
		jsonx = json.load(f)
		width = int(jsonx['imageWidth'])
		height = int(jsonx['imageHeight'])
		shapes = jsonx['shapes']
		with open(str(j).replace('demo3/wrong', 'wrongout').replace('json', 'txt'), 'w') as fw:
			for shape in shapes:
				if shape['label'] == 'roi':
					points = np.array(shape['points'])
					xmin = int(points[0][0])
					xmax = int(points[0][0])
					ymin = int(points[0][1])
					ymax = int(points[0][1])
					for point in shape['points']:
						if point[0] > xmax:
							xmax = point[0]
						if point[0] < xmin:
							xmin = point[0]
						if point[1] > ymax:
							ymax = point[1]
						if point[1] < ymin:
							ymin = point[1]
					bb = convert_2((width, height), (xmin, xmax, ymin, ymax))
					fw.write('0 ' + ''.join([str(a)+' ' for a in bb]))
				if shape['shape_type'] == 'point':
					point = np.array(shape['points'][0])
					fw.write(f' {point[0]/width} {point[1]/height} 2')
			fw.write('\n')
			fw.close()
		f.close()

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐