如何将指定CSV标注文件转换为YOLO格式?含代码集成与平台选择疑问
把CSV标注转成YOLO格式的完整步骤
一、先搞懂YOLO标注规则
YOLO的标注是每个图片对应一个同名的.txt文件,每行格式为:
<整数类ID> <归一化x中心> <归一化y中心> <归一化宽度> <归一化高度>
所有坐标值必须是0-1之间的小数(相对于图片的宽高做归一化)。
二、你的CSV字段对应转换逻辑
你的CSV字段和YOLO参数的对应关系:
- 原
class列:直接取整作为YOLO的类ID(比如3.0→3) - 原
xmin/xmax:用来计算边界框的宽度和x中心;ymin/ymax计算高度和y中心 - 必须先获取对应图片的实际宽度W和高度H才能做归一化
转换公式:
x_center = (xmin + xmax) / (2 * W) y_center = (ymin + ymax) / (2 * H) width = (xmax - xmin) / W height = (ymax - ymin) / H
三、具体实现代码(Python)
把下面的代码保存为csv2yolo.py,按注释修改路径即可使用:
import csv from PIL import Image import os # -------------------------- 配置参数 -------------------------- CSV_PATH = "你的标注文件.csv" # 替换成你的CSV文件路径 IMAGE_FOLDER = "存放图片的文件夹路径" # 替换成你的图片所在文件夹 OUTPUT_FOLDER = "生成YOLO标注的文件夹" # 输出txt的文件夹,会自动创建 # ------------------------------------------------------------- # 创建输出文件夹 os.makedirs(OUTPUT_FOLDER, exist_ok=True) # 按图片分组存储标注 image_annotations = {} # 读取CSV with open(CSV_PATH, 'r', encoding='utf-8') as f: reader = csv.DictReader(f) for row in reader: img_name = row['image_path'] # 整理当前标注的信息 annot = { 'class_id': int(float(row['class'])), 'xmin': float(row['xmin']), 'xmax': float(row['xmax']), 'ymin': float(row['ymin']), 'ymax': float(row['ymax']) } # 按图片名分组 if img_name not in image_annotations: image_annotations[img_name] = [] image_annotations[img_name].append(annot) # 生成YOLO标注文件 for img_name, annots in image_annotations.items(): # 获取图片尺寸 img_path = os.path.join(IMAGE_FOLDER, img_name) try: with Image.open(img_path) as img: W, H = img.size except FileNotFoundError: print(f"警告:未找到图片 {img_path},跳过该图片的标注生成") continue # 生成txt内容 txt_content = [] for annot in annots: x_center = (annot['xmin'] + annot['xmax']) / (2 * W) y_center = (annot['ymin'] + annot['ymax']) / (2 * H) width = (annot['xmax'] - annot['xmin']) / W height = (annot['ymax'] - annot['ymin']) / H # 保留6位小数足够,避免冗余 txt_line = f"{annot['class_id']} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}" txt_content.append(txt_line) # 写入txt文件 txt_path = os.path.join(OUTPUT_FOLDER, os.path.splitext(img_name)[0] + '.txt') with open(txt_path, 'w', encoding='utf-8') as f: f.write('\n'.join(txt_content)) print("转换完成!所有YOLO标注已保存到", OUTPUT_FOLDER)
四、运行步骤
- 安装依赖:打开终端/命令提示符,运行
pip install pillow - 修改代码里的三个路径(CSV_PATH、IMAGE_FOLDER、OUTPUT_FOLDER)
- 执行代码:
python csv2yolo.py
五、适用平台
Windows、macOS、Linux都可使用,只要安装了Python 3.6及以上版本。
内容的提问来源于stack exchange,提问作者Simran Taneja
相关产品推荐
相关产品推荐

