python yolo数据转coco

news/2024/7/10 23:01:20 标签: YOLO, 人工智能

yolo数据集格式

dataset_yolo
    images
        |--train
        |--test
        |--val
    labels
        |--train
        |--test
        |--val

yolo2coco.py

from genericpath import exists
import os
import json
from PIL import Image
 
# 设置数据集路径
dataset_path = "./dataset_1223_yolo"
images_path = os.path.join(dataset_path, "images")
labels_path = os.path.join(dataset_path, "labels")

save_dir="output"
os.makedirs(save_dir,exist_ok=True)

# 类别映射
categories = [
    {"id": 1, "name": "yb_text"},
    {"id": 2, "name": "kk_text"},
    {"id": 3, "name": "zsd_text"},
    {"id": 4, "name": "xn_text"},
    {"id": 5, "name": "controls_text"},
    {"id": 6, "name": "water_mark"},
    # 添加更多类别
]
 
# YOLO格式转COCO格式的函数
def convert_yolo_to_coco(x_center, y_center, width, height, img_width, img_height):
    x_min = (x_center - width / 2) * img_width
    y_min = (y_center - height / 2) * img_height
    width = width * img_width
    height = height * img_height
    return [x_min, y_min, width, height]
 
# 初始化COCO数据结构
def init_coco_format():
    return {
        "images": [],
        "annotations": [],
        "categories": categories
    }
 

suffixes=('.png', '.jpg')

# 处理每个数据集分区
for split in ['train', 'test', 'val']:
    coco_format = init_coco_format()
    annotation_id = 1
    
    folder_path=os.path.join(images_path, split)
    if not os.path.exists(folder_path):
        continue 
    for img_name in os.listdir(folder_path):
        if img_name.lower().endswith(suffixes):
            img_path = os.path.join(images_path, split, img_name)
            label_path = os.path.join(labels_path, split, os.path.splitext(img_name)[0]+".txt")
 
            img = Image.open(img_path)
            img_width, img_height = img.size
            image_info = {
                "file_name": img_name,
                "id": len(coco_format["images"]) + 1,
                "width": img_width,
                "height": img_height
            }
            coco_format["images"].append(image_info)
 
            if os.path.exists(label_path):
                with open(label_path, "r") as file:
                    for line in file:
                        category_id, x_center, y_center, width, height = map(float, line.split())
                        bbox = convert_yolo_to_coco(x_center, y_center, width, height, img_width, img_height)
                        annotation = {
                            "id": annotation_id,
                            "image_id": image_info["id"],
                            "category_id": int(category_id) + 1,
                            "bbox": bbox,
                            "area": bbox[2] * bbox[3],
                            "iscrowd": 0
                        }
                        coco_format["annotations"].append(annotation)
                        annotation_id += 1
 
    # 为每个分区保存JSON文件
    with open(f"{save_dir}/{split}_coco_format.json", "w") as json_file:
        json.dump(coco_format, json_file, indent=4)


http://www.niftyadmin.cn/n/5331468.html

相关文章

使用Python的学生信息管理系统

import re # 导入正则表达式模块 import os # 导入操作系统模块filename "students.txt" # 定义保存学生信息的文件名def menu():# 输出菜单print(╔————————————————学生信息管理系统—————————————————╗│ …

质数与约数

1、质数的判定——试除法 bool is_prime(int n) {if (n < 2) return false;//for循环中写成 i * i < n 可能会造成溢出for (int i 2; i < n / i; i) {if (n % i 0) return false;}return true; } 2、分解质因数——试除法 void divide(int n) {//n最多有一个大于…

设计大师的秘密武器:色彩搭配的奇妙技巧

在设计中&#xff0c;色彩搭配扮演着至关重要的角色。色彩搭配的选择和设计是设计师创作过程中不可或缺的一部分。本文将介绍色彩搭配的重要性&#xff0c;如何设计出令人惊叹的色彩搭配以及色彩对设计师的作用。 色彩卡 | 一个覆盖广泛主题工具的高效在线平台(amd794.com) h…

使用 Elasticsearch 和 LlamaIndex 进行高级文本检索:句子窗口检索

2023 年是检索增强生成 (RAG) 的一年&#xff0c;人们探索了许多用例&#xff0c;并使用该技术开发了数百种产品。 从 Q/A 聊天机器人到基于上下文的代理&#xff0c;RAG 的使用一直是 LLM 申请快速增长的主要因素。 支持不断发展的社区以及 Langchain 和 LlamaIndex 等强大框架…

基于Mapbox的Mvt矢量瓦片集成实践

目录 前言 一、数据说明 1、基本数据 2、属性数据 二、Mapbox集成Mvt矢量瓦片 1、关于访问令牌 2、定义html 3、初始地图 4、加载矢量瓦片 5、效果展示 总结 前言 熟悉矢量瓦片的朋友一定知道&#xff0c;在Webgis当中&#xff0c;矢量瓦片的格式除了pbf的格式&#x…

数字化工厂管理系统发展的三大方向

随着科技的快速发展&#xff0c;数字化工厂管理系统已经成为工业制造领域的重要趋势。数字化工厂管理系统通过集成三维设计、生产控制和企业管理等功能&#xff0c;实现了产品全生命周期的智能化和自动化。在未来的发展中&#xff0c;数字化工厂管理系统将朝着更加高效、灵活和…

Git版本控制——分支

分支 几乎所有的版本控制系统都以某种形式支持分支。 使用分支意味着可以把工作从开发主线上分离开来进行重大的Bug修改、开发新的功能&#xff0c;以免影响开发主线。 查看本地分支 git branch创建本地分支 git branch 分支名切换分支(checkout) git checkout 分支名创建…

Angular系列教程之变更检测与性能优化

文章目录 前言变更检测的原理脏检查OnPush策略 示例代码总结 前言 Angular 除了默认的变化检测机制&#xff0c;也提供了ChangeDetectionStrategy.OnPush&#xff0c;用 OnPush 可以跳过某个组件或者某个父组件以及它下面所有子组件的变化检测。 在本文中&#xff0c;我们将探…