You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取CSV文件并将值传入yolo_to_coco函数后导出结果

解决方案

以下是实现批量转换并保存结果的完整代码:

import csv

def yolo_to_coco(x_center, y_center, w, h, image_w, image_h):
    w = w * image_w
    h = h * image_h
    x1 = ((2 * x_center * image_w) - w) / 2
    y1 = ((2 * y_center * image_h) - h) / 2
    return [x1, y1, w, h]

# 自行指定图片宽高
IMAGE_WIDTH = 1024
IMAGE_HEIGHT = 1024

# 输入输出文件路径
input_csv_path = "input.csv"
output_csv_path = "output.csv"

with open(input_csv_path, "r", encoding="utf-8") as infile, open(output_csv_path, "w", newline="", encoding="utf-8") as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    
    # 可选:写入表头
    writer.writerow(["x1", "y1", "w", "h"])
    
    for row in reader:
        # 处理单列中每行的四个数值(假设每行数据用逗号分隔)
        if not row:
            continue  # 跳过空行
        data = row[0].split(",")
        if len(data) != 4:
            print(f"跳过无效行:{row}")
            continue
        # 转换为浮点数
        try:
            x_center = float(data[0].strip())
            y_center = float(data[1].strip())
            w = float(data[2].strip())
            h = float(data[3].strip())
        except ValueError:
            print(f"跳过格式错误行:{row}")
            continue
        # 调用转换函数
        result = yolo_to_coco(x_center, y_center, w, h, IMAGE_WIDTH, IMAGE_HEIGHT)
        # 写入结果
        writer.writerow(result)

print(f"转换完成,结果已保存到 {output_csv_path}")

关键说明:

  1. 路径配置:修改input_csv_path和output_csv_path为你的实际文件路径
  2. 数值分割:如果CSV每行数据用空格分隔,将data = row[0].split(",")改为data = row[0].split()
  3. 异常处理:代码会自动跳过空行和格式错误的行,并打印提示信息
  4. 表头设置:不需要表头的话,可删除writer.writerow(["x1", "y1", "w", "h"])这一行

内容的提问来源于stack exchange,提问作者user181925

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 00:05:28