当前位置: 首页 > news >正文

[已解决]Python将COCO格式实例分割数据集转换为YOLO格式

直接根据代码更换自己成为自己的路径便可以转换

import json
import os
import numpy as np
from pycocotools import mask as coco_mask# 加载 COCO 数据集
coco_path = "/COCO2017/annotations/instances_train2017.json"
with open(coco_path, "r") as f:coco_data = json.load(f)# 创建保存 YOLO 标注的目录
output_dir = "/COCO2017/labels/train2017"
os.makedirs(output_dir, exist_ok=True)# 创建类别索引映射
category_id_to_index = {cat["id"]: idx for idx, cat in enumerate(coco_data["categories"])}# 创建图像ID到图像信息的映射
image_info_map = {img["id"]: img for img in coco_data["images"]}def rle_to_polygon(rle_segmentation, img_width, img_height):"""将RLE格式转换为多边形"""try:rle = coco_mask.frPyObjects(rle_segmentation, img_height, img_width)binary_mask = coco_mask.decode(rle)# 简单的轮廓提取(简化版)polygons = []# 这里需要更复杂的轮廓提取算法,暂时返回空列表return polygonsexcept:return []# 按图像ID组织标注
annotations_by_image = {}
for annotation in coco_data["annotations"]:image_id = annotation["image_id"]if image_id not in annotations_by_image:annotations_by_image[image_id] = []annotations_by_image[image_id].append(annotation)# 遍历每个图像的标注
for image_id, annotations in annotations_by_image.items():if image_id not in image_info_map:continueimage_info = image_info_map[image_id]image_width = image_info["width"]image_height = image_info["height"]image_filename = image_info["file_name"].split(".")[0]label_filename = os.path.join(output_dir, f"{image_filename}.txt")with open(label_filename, "w") as f:for annotation in annotations:category_id = annotation["category_id"]class_index = category_id_to_index[category_id]segmentation = annotation["segmentation"]polygons = []if isinstance(segmentation, dict):# RLE格式polygons = rle_to_polygon(segmentation, image_width, image_height)if not polygons:continueelif isinstance(segmentation, list) and segmentation:# 多边形格式polygons = segmentationelse:continuefor poly in polygons:if len(poly) < 6:continuenormalized_coords = []for i in range(0, len(poly), 2):if i + 1 < len(poly):x = max(0.0, min(1.0, poly[i] / image_width))y = max(0.0, min(1.0, poly[i + 1] / image_height))normalized_coords.extend([x, y])if len(normalized_coords) >= 6:coords_str = " ".join([f"{coord:.6f}" for coord in normalized_coords])f.write(f"{class_index} {coords_str}\n")print("转换完成!")

效果:

http://www.dtcms.com/a/537341.html

相关文章:

  • CSS Backgrounds (背景)
  • Blender入门学习08 - 骨骼绑定
  • 家装设计网站开发企业做网站大概多少钱
  • TCP/UDP端口、IP协议号与路由协议 强行记忆点总结
  • (一)React面试()
  • 配置文件加载顺序与优先级规则
  • 数字化转型迫在眉睫,企业应该如何面对?
  • 做网站百度云网站登录不了
  • HF4054H-B 50V耐压 集成6.1V过压保护和1.3A过流保护 42V热拔插性能的500mA锂电池线性充电芯片
  • 网站可以做音频线吗网站如何安装源码
  • 小学校园文化建设网站网站打不开显示asp
  • 142.DDR报错bank32,33,34
  • Android性能优化深度解析与实际案例
  • 网站素材网站建设的目标和需求
  • 与您探讨电子元器件结构陶瓷(陶瓷基板)的分类及结构陶瓷的应用
  • 模板建站自适应互联网网站分了
  • 苹果ios安卓apk应用APP文件怎么修改手机APP显示的名称
  • 网站界面用什么做的网站创建方法
  • 《自动控制原理》第 3 章 线性控制系统的运动分析:3.6、3.7
  • 特征选择中的统计思维:哪些变量真的重要?
  • 项目七 使用ODL Yang UI操作流表
  • 电子商务网站怎么建料远若近网站建设
  • [CSP-S 2024] 超速检测
  • 基于MT5的K线处理逻辑
  • 河南郑州网站建设哪家公司好免费wordpress主题下载地址
  • 低空经济网络安全的政策体系构建
  • 网页设计网站规划深圳设计网站公司哪家好
  • 【Etcd 】Etcd 详解以及安装教程
  • 文交所网站建设方案饰品企业网站建设
  • 郑州网站建设市场陕西省建设工程信息网官网