csv文件转换yolo格式

Python代码

import os
import csv

def convert_csv_to_yolo(csv_file, output_dir):
    with open(csv_file, 'r') as file:
        reader = csv.DictReader(file)
        for row in reader:
            filename = row['filename']
            width = int(row['width'])
            height = int(row['height'])
            class_label = row['class']
            xmin = int(row['xmin'])
            ymin = int(row['ymin'])
            xmax = int(row['xmax'])
            ymax = int(row['ymax'])

            # 计算YOLO坐标
            x_center = (xmin + xmax) / (2 * width)
            y_center = (ymin + ymax) / (2 * height)
            bbox_width = (xmax - xmin) / width
            bbox_height = (ymax - ymin) / height

            # 构建YOLO格式字符串
            yolo_line = f"{class_label} {x_center} {y_center} {bbox_width} {bbox_height}\n"

            # 构建输出文件路径
            output_file = os.path.join(output_dir, filename + '.txt')

            # 将YOLO格式字符串写入文件
            with open(output_file, 'a') as output:
                output.write(yolo_line)

def batch_convert_csv_to_yolo(csv_folder, output_dir):
    csv_files = [f for f in os.listdir(csv_folder) if f.endswith('.csv')]
    for csv_file in csv_files:
        csv_file_path = os.path.join(csv_folder, csv_file)
        print(f"Converting {csv_file} to YOLO format:")
        convert_csv_to_yolo(csv_file_path, output_dir)
        print()

# 指定包含CSV文件的文件夹路径
csv_folder_path = ''

# 指定输出文件夹路径
output_folder_path = ''

# 执行批量转换
batch_convert_csv_to_yolo(csv_folder_path, output_folder_path)

示例图

转换前

csv文件

转换后

txt(yolo格式)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值