COCO-to-YOLO-Segmentation-Converter
CVAT 标注的分割数据集导出为 YOLO的格式不对,只能中转一下:
- CVAT 导出为 COCO 的格式;
- 使用本脚本将导出的 COCO 格式转换为 YOLO 格式的 txt;
概述
这是一个简单的Python脚本,用于将COCO格式的分割标注转换为YOLO格式的分割标注。该脚本使用了标准库中的argparse
模块来处理命令行参数,从而使得用户能够方便地指定JSON文件路径以及输出文件夹。
安装
确保您的环境中安装了Python 3.x。此外,此脚本不依赖于任何外部库,因此无需额外安装其他包。
使用方法
- 克隆或下载此仓库。
- 确保您有一个有效的COCO格式的JSON文件。
- 运行脚本并传入必要的参数。
命令行参数
json_file
: 必填参数,指定包含COCO格式数据的JSON文件路径。--output_folder
或-o
: 可选参数,默认值为labels
,用于指定输出YOLO格式标注的文件夹名称。
示例
python script_name.py path/to/coco_annotations.json --output_folder output_folder_name
或者,如果您不想指定输出文件夹名称,则可以使用默认值:
python script_name.py path/to/coco_annotations.json
脚本功能
- 加载COCO JSON文件: 从指定路径加载COCO JSON文件。
- 转换标注: 将COCO格式的分割标注转换为YOLO格式。
- 保存标注: 将转换后的YOLO格式标注保存到指定的输出文件夹。
import argparse
import json
import os
def convert_coco_to_yolo_segmentation(json_file, output_folder="labels"):
"""
将 COCO 格式的分割标注转换为 YOLO 格式。
:param json_file: str, 包含 COCO 格式数据的 JSON 文件路径。
:param output_folder: str, 输出 YOLO 格式标注的文件夹名。
"""
# 加载 JSON 文件
with open(json_file, 'r') as file:
coco_data = json.load(file)
# 创建输出文件夹以存储 YOLO 分割标注
output_folder_path = os.path.join(os.path.dirname(json_file), output_folder)
os.makedirs(output_folder_path, exist_ok=True)
# 提取 COCO JSON 数据中的标注
annotations = coco_data['annotations']
# 构建图像 ID 到图像元数据的映射表
images_dict = {image['id']: image for image in coco_data['images']}
for annotation in annotations:
image_id = annotation['image_id']
category_id = annotation['category_id']
segmentation = annotation['segmentation']
# bbox = annotation['bbox']
# 查找图像文件名
if image_id not in images_dict:
print(f"警告: 图像 ID {image_id} 在 COCO 数据中未找到。")
continue
image = images_dict[image_id]
image_filename = os.path.splitext(os.path.basename(image['file_name']))[0]
image_width = image['width']
image_height = image['height']
# 将 COCO 分割转换为 YOLO 分割格式
yolo_segmentation = [
f"{x / image_width:.5f} {y / image_height:.5f}"
for x, y in zip(segmentation[0][::2], segmentation[0][1::2])
]
yolo_segmentation = ' '.join(yolo_segmentation)
# 生成 YOLO 分割标注行
yolo_annotation = f"{category_id - 1} {yolo_segmentation}"
# 保存 YOLO 分割标注到文件
output_filename = os.path.join(output_folder_path, f"{image_filename}.txt")
with open(output_filename, 'a+') as file:
file.write(yolo_annotation + '\n')
print("转换完成。YOLO 分割标注已保存至 'labels' 文件夹。")
def main():
"""
主函数,用于执行脚本。
"""
parser = argparse.ArgumentParser(description='将 COCO 格式的分割标注转换为 YOLO 格式。')
parser.add_argument('json_file', type=str, help='包含 COCO 格式数据的 JSON 文件路径。')
parser.add_argument('--output_folder', type=str, default='labels', help='输出 YOLO 格式标注的文件夹名。')
args = parser.parse_args()
convert_coco_to_yolo_segmentation(args.json_file, args.output_folder)
if __name__ == "__main__":
main()