yolo格式转labelme格式并验证

  • yolo格式转labelme格式
  • python to_json.py yolo标签路径 labelme标签路径
import os, sys, json, shutil
import cv2
from glob import glob
import numpy as np

classes=['white', 'yellow', 'black']

def func(labels, w, h, jp):
	dic={}
	dic['version'] = '5.0.1'
	dic['flags'] = {}
	dic['imageData'] = None
	dic['imagePath'] = jp
	dic['imageHeight'] = h
	dic['imageWidth'] = w
	dic['shapes'] = []
	if labels is not None: 
		for l in labels:
			tmp = {}
			tmp['label'] = classes[l[0]]
			tmp['points'] =[[str(l[1]), str(l[2])], [str(l[3]), str(l[4])]]
			tmp['group_id']= None
			tmp['shape_type'] = 'rectangle'
			tmp['flags'] = {}
			dic['shapes'].append(tmp)
	with open(jp, 'w') as f: json.dump(dic, f)

txt_path=sys.argv[1]
json_path=sys.argv[2]

txts=glob(txt_path+'/*txt')
txts.sort()

for t in txts:
	print(t)
	jp=t.split('/')[-1]
	jp=json_path+'/'+jp[:-3]+'json'
	im = t[:-3]+'jpg'
	shutil.copy(im, json_path)
	im = cv2.imread(im)
	h,w,c = im.shape
	labels = np.loadtxt(t).reshape(-1, 5)
	if len(labels) > 0: 
		labels[:,1::2] = w * labels[:, 1::2]
		labels[:,2::2] = h * labels[:, 2::2]
		lab=labels.copy()
		lab[:, 1] = np.clip(labels[:, 1] - labels[:, 3]/2, 0, w)
		lab[:, 2] = np.clip(labels[:, 2] - labels[:, 4]/2, 0, h)
		lab[:, 3] = np.clip(labels[:, 1] + labels[:, 3]/2, 0, w)
		lab[:, 4] = np.clip(labels[:, 2] + labels[:, 4]/2, 0, h)
		func(lab.astype(np.int), w, h, jp)
	else:
		func(None, w, h, jp)
	#break
  • 验证
  • python look_json.py labelme标签路径
import os, sys, json, shutil
import cv2
from glob import glob

classes=['white', 'yellow', 'black']
colors=[(0,0,255), (0,255,0), (255,0,0)]

path=sys.argv[1]
al=glob(path+'/*json')
al.sort()
for a in al:
	b=a[:-4]+'jpg'
	im=cv2.imread(b)
	l=json.load(open(a, 'r'))
	shapes=l['shapes']
	for s in shapes:
		p=s['points']
		x1=int(p[0][0])
		y1=int(p[0][1])
		x2=int(p[1][0])
		y2=int(p[1][1])
		i = classes.index(s['label'])
		cv2.rectangle(im, (x1,y1), (x2,y2), colors[i], 1)
		font = cv2.FONT_HERSHEY_SIMPLEX
		cv2.putText(im, s['label'], (x1-2,y1-2), font, 0.4, colors[i], thickness=1)
	cv2.imshow('ss', im)
	ch = cv2.waitKey() & 0xff
	if ch == 27: break