代码
import os
import json
import cv2
# 文件夹路径
images_folder = 'images'
labels_folder = 'labels'
output_folder = 'labels_txt'
# 创建输出文件夹
os.makedirs(output_folder, exist_ok=True)
# 获取所有图片文件名(假设图片文件格式为jpg)
image_files = [f for f in os.listdir(images_folder) if f.endswith('.jpg')]
# 处理每一个图片文件和对应的JSON文件
for image_file in image_files:
# 获取文件前缀名
file_prefix = os.path.splitext(image_file)[0]
# 构建图片文件和JSON文件路径
image_path = os.path.join(images_folder, image_file)
json_path = os.path.join(labels_folder, f"{file_prefix}.json")
# 读取图片尺寸
image = cv2.imread(image_path)
image_height, image_width, _ = image.shape
# 读取JSON文件
with open(json_path, 'r') as file:
data = json.load(file)
# 准备YOLO格式的数据
yolo_data = []
for shape in data['shapes']:
label = shape['label']
if label == "vehicle":
points = shape['points']
# 归一化坐标
normalized_points = []
for point in points:
normalized_x = point[0] / image_width
normalized_y = point[1] / image_height
normalized_points.extend([normalized_x, normalized_y])
# YOLO格式:class_index x1 y1 x2 y2 x3 y3 x4 y4
yolo_data.append(f"0 {' '.join(map(str, normalized_points))}")
# 写入YOLO格式标签文件
yolo_file_path = os.path.join(output_folder, f"{file_prefix}.txt")
with open(yolo_file_path, 'w') as file:
file.write("\n".join(yolo_data))
print("所有YOLO格式标签文件已生成。")