如何批量修改YOLOv8生成的人像标注:将person拆分为三类?
如何批量将YOLOv8检测出的"person"标注分类为man/woman/child
我有大量含有人像的图片,用YOLOv8检测后所有标注类别都是0类"person",现在需要把这些标注按图像内容改成三类:0类"man"、1类"woman"、2类"child"。手动修改太耗时,求最简实现方法。
原标注示例
0 0.912747 0.641636 0.173486 0.701598 0 0.711514 0.368986 0.127007 0.269725 0 0.353645 0.612958 0.214726 0.653104 0 0.294899 0.279542 0.154637 0.497855
期望修改后的标注示例
1 0.912747 0.641636 0.173486 0.701598 0 0.711514 0.368986 0.127007 0.269725 2 0.353645 0.612958 0.214726 0.653104 0 0.294899 0.279542 0.154637 0.497855
可行解决方案
方法1:自动分类批量更新(效率最高)
用预训练的视觉分类模型对每个检测到的人物区域二次分类,自动替换标注类别:
- 遍历所有图像和对应的YOLO标注文件
- 从原图中裁剪出每个标注框对应的人物区域
- 用分类模型判断该区域属于man/woman/child
- 替换标注中的类别ID并保存新文件
以下是简化的Python实现代码:
import os import cv2 from ultralytics import YOLO # 加载YOLOv8分类模型(也可以用专门的性别/年龄分类模型) classifier = YOLO('yolov8n-cls.pt') # 自定义类别映射规则,可根据模型输出调整 category_mapping = { 'male': 0, 'man': 0, 'female': 1, 'woman': 1, 'child': 2, 'boy': 2, 'girl': 2 } # 配置路径 img_dir = "你的图片目录路径" label_dir = "原标注文件目录路径" new_label_dir = "新标注文件保存路径" os.makedirs(new_label_dir, exist_ok=True) # 批量处理 for label_filename in os.listdir(label_dir): if not label_filename.endswith('.txt'): continue img_path = os.path.join(img_dir, label_filename.replace('.txt', '.jpg')) if not os.path.exists(img_path): continue img = cv2.imread(img_path) img_h, img_w = img.shape[:2] with open(os.path.join(label_dir, label_filename), 'r') as f: original_lines = f.readlines() updated_lines = [] for line in original_lines: parts = line.strip().split() if len(parts) != 5: updated_lines.append(line) continue # 解析YOLO归一化标注,转换为像素坐标 _, x_center, y_center, box_w, box_h = map(float, parts) x1 = int((x_center - box_w/2) * img_w) y1 = int((y_center - box_h/2) * img_h) x2 = int((x_center + box_w/2) * img_w) y2 = int((y_center + box_h/2) * img_h) # 裁剪人物区域 person_crop = img[y1:y2, x1:x2] if person_crop.size == 0: updated_lines.append(line) continue # 预测分类 results = classifier(person_crop) top_label = results[0].names[results[0].probs.top1] # 映射到目标类别,无法匹配时默认保留原0类 new_cls = category_mapping.get(top_label.lower(), 0) # 生成新标注行 updated_line = f"{new_cls} {' '.join(parts[1:])}\n" updated_lines.append(updated_line) # 保存新标注 with open(os.path.join(new_label_dir, label_filename), 'w') as f: f.writelines(updated_lines)
方法2:半自动化标注工具辅助(精度可控)
用支持YOLO格式的标注工具(如LabelImg、LabelStudio)批量加载图像和原标注,工具会自动显示所有person框,你只需快速选择对应类别即可完成标注更新,比纯手动效率提升数倍,适合对精度要求极高的场景。
方法3:GPT-4V视觉能力辅助(小批量场景)
如果图片数量较少,可直接将图片+对应标注片段上传给GPT-4V,让它输出修改后的标注内容;批量处理可调用GPT-4V API,传入裁剪后的人物图获取分类结果,再更新标注文件。
内容的提问来源于stack exchange,提问作者Nada
相关产品推荐
相关产品推荐

