import json
import os
# 定义标签映射
label_map = {
"background": 0,
"di": 1
}
def convert_labelme_to_yolo(json_path, output_dir):
try:
with open(json_path, 'r', encoding='utf-8') as f:
labelme_data = json.load(f)
image_width = labelme_data['imageWidth']
image_height = labelme_data['imageHeight']
yolo_annotations = []
for shape in labelme_data['shapes']:
label = shape['label']
if label not in label_map:
continue # 忽略未定义的标签
class_id = label_map[label]
points = shape['points']
if shape['shape_type'] == 'rectangle':
(x1, y1), (x2, y2) = points
elif shape['shape_type'] == 'polygon':
x1, y1 = min(point[0] for point in points), min(point[1] for point in points)
x2, y2 = max(point[0] for point in points), max(point[1] for point in points)
elif shape['shape_type'] == 'circle':
# YOLO不直接支持圆形,转为最小外接矩形
(x_center, y_center), (x_radius, _) = points
x1 = x_center - x_radius
y1 = y_center - x_radius
x2 = x_center + x_radius
y2 = y_center + x_radius
elif shape['shape_type'] == 'line':
# 线条转为最小矩形框,便于YOLO处理
x1, y1 = min(point[0] for point in points), min(point[1] for point in points)
x2, y2 = max(point[0] for point in points), max(point[1] for point in points)
else:
continue # 其他类型不处理
# 归一化并计算中心坐标和宽高
x_center = (x1 + x2) / 2.0 / image_width
y_center = (y1 + y2) / 2.0 / image_height
width = (x2 - x1) / image_width
height = (y2 - y1) / image_height
# 保存YOLO格式标注
yolo_annotations.append(f"{class_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}")
# 输出到txt文件
output_file = os.path.join(output_dir, os.path.splitext(os.path.basename(json_path))[0] + '.txt')
with open(output_file, 'w') as f:
f.write('\n'.join(yolo_annotations))
print(f"Successfully converted: {json_path}")
except Exception as e:
print(f"Error processing {json_path}: {e}")
def process_folder(input_folder, output_folder):
# 创建输出文件夹(如果不存在)
os.makedirs(output_folder, exist_ok=True)
# 处理输入文件夹中的每个 JSON 文件
for filename in os.listdir(input_folder):
if filename.endswith(".json"):
json_path = os.path.join(input_folder, filename)
convert_labelme_to_yolo(json_path, output_folder)
# 修改成自己的地址
input_folder = "D:\LanKao\HuiAnjson\yifengjson" # labelme标注的json标签文件地址
output_folder = "D:/LanKao/HuiAnjson/YiFengyolo_labels" # 转换为yolo模型需要的数据集格式
process_folder(input_folder, output_folder)
# 列出输出文件夹中的文件以确认
output_files = os.listdir(output_folder)
print("Generated YOLO label files:", output_files)
json文件转换为.txt格式(可运行,检测任务用)
于 2024-10-16 17:42:33 首次发布