在这里推荐我常用的标注工具 VIA。用久了,很多转化脚本都是基于这个工具导出的格式,所以没用其他标注工具了。
VIA可以在线标注,地址是:http://www.robots.ox.ac.uk/~vgg/software/via/via.html
标注完数据后,保存项目,导出一份json。
下面代码把该json转换成YOLOv5所需的标注格式
import os
import json
anno_file_path = '' // json路径
saveFolder = r'./txt'
if not os.path.exists(saveFolder):
os.mkdir(saveFolder)
annotations = json.load(open(anno_file_path, 'r', encoding='UTF-8'))
imgs = annotations["_via_img_metadata"]
// 因为yolov5的标注数据格式是用比例的,需要输入图片的宽高
WIDTH = 960
HEIGHT = 540
// 这里为了简单,统一把所有数据标注为类别2
objClass = 2
# 遍历每个图片
for imgId in imgs:
filename = imgs[imgId]['filename']
imgName = filename.split('.')[0]
print('filename:', filename)
regions = imgs[imgId]['regions']
if len(regions) <= 0:
continue
data = ''
# 遍历每个区域
for region in regions:
print(region)
shape = region['shape_attributes']
x = shape['x']
y = shape['y']
boxW = shape['width']
boxH = shape['height']
minX = int(x)
minY = int(y)
maxX = int(x + boxW)
maxY = int(y + boxH)
centerX = round((minX + maxX) / 2 / WIDTH, 6)
centerY = round((minY + maxY) / 2 / HEIGHT, 6)
w = round((maxX - minX) / WIDTH, 6)
h = round((maxY - minY) / HEIGHT, 6)
data = f'{objClass} {centerX} {centerY} {w} {h}\n'
file = open(f'{saveFolder}/{imgName}.txt', 'w')
file.write(data[:-1])
file.close()
上面脚本会把VIA导出的json文件生成N个标注文件,N为标注的图片数量。
最后把标注文件和图片按这样的目录结构存放即可。