一、label:txt格式转json格式
MMYOLO提供脚本将 labelme 的 label 转换为 COCO label:
检查转换的COCO label:
二、label:json格式转yolo(txt)格式
json格式label形式如下:比较重要的信息有,“label”即类别id,“points”即目标框角点坐标,分别指[左上角x坐标,左上角y坐标],[右下角x坐标,右下角y坐标]
yolo格式说明:
数据格式:类别id 中心点x坐标 中心点y坐标 w h(相对于图片宽高)
x= (shape['points'][0][0] + shape['points'][1][0]) / 2 / data['imageWidth']
y= (shape['points'][0][1] + shape['points'][1][1]) / 2 / data['imageHeight']
w= (shape['points'][1][0] - shape['points'][0][0]) / data['imageWidth']
h= (shape['points'][1][1] + shape['points'][0][1]) / data['imageHeight']
代码如下:
import os
import json
def json_to_yolo(json_path, txt_path, label_list):
with open(json_path, 'r') as f:
data = json.load(f)
with open(txt_path, 'w') as f:
for shape in data['shapes']:
if shape['label'] in label_list:
x1 = shape['points'][0][0] / data['imageWidth']
y1 = shape['points'][0][1] / data['imageHeight']
x2 = shape['points'][1][0] / data['imageWidth']
y2 = shape['points'][1][1] / data['imageHeight']
x3=(x1+x2)/2
y3=(y1+y2)/2
label = label_list.index(shape['label']) #类别id
f.write(f"{label} {x3} {y3} {x2-x1} {y2-y1}\n")
label_list = ['cat'] # 标签列表 此代码测试数据集为单类别
input_folder = 'json格式label所在目录'
output_folder = '得到的txt格式label输出目录'
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for filename in os.listdir(input_folder):
if filename.endswith('.json'):
json_path = os.path.join(input_folder, filename)
txt_path = os.path.join(output_folder, os.path.splitext(filename)[0] + '.txt')
json_to_yolo(json_path, txt_path, label_list)
检测转换的txt label:思路就是,将txt文件里的中心点坐标,标注到对应图片中上,代码如下:
import os
import cv2
# 创建新的文件夹用于存放标注后的图片
output_folder = '标注好的图片的输出目录'
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 获取txt文件夹中的所有txt文件
txt_folder = r'存放txt格式label的文件夹目录'
txt_files = [f for f in os.listdir(txt_folder) if f.endswith('.txt')]
# 遍历每个txt文件
for txt_file in txt_files:
# 读取对应的图片文件,图片name和txt文件name一致
image_file = os.path.splitext(txt_file)[0] + '.jpg'
image_path = os.path.join(r'图片所在文件夹目录', image_file)
if os.path.exists(image_path):
# 读取图片
image = cv2.imread(image_path)
# 读取txt文件中的标注数据
with open(os.path.join(txt_folder, txt_file), 'r') as f:
data = f.readline().split()
x = float(data[1])
y = float(data[2])
# 将(x,y)坐标对应的点标注到图片上
x_pixel = int(x * image.shape[1])
y_pixel = int(y * image.shape[0])
cv2.circle(image, (x_pixel, y_pixel), 5, (0, 0, 255), -1)
# 保存生成的图片到新的文件夹中
output_file = os.path.join(output_folder, image_file)
cv2.imwrite(output_file, image)
else:
print("对应的图片文件{}不存在".format(image_path))
print("可视化操作完成,生成的图片存放在{}文件夹中".format(output_folder))
结果如下:每个红点点都在猫的中心位置,转换成功!