YOLO格式数据转coco格式数据

import os
import json
import cv2
import random
import time
from PIL import Image

coco_format_save_path = '/home/rendoudou/datasets/yolo2coco-new/json'  # 要生成的标准coco格式标签所在文件夹
yolo_format_classes_path = 'name.txt'  # 类别文件,一行一个类
yolo_format_annotation_path = '/home/rendoudou/datasets/yolo2coco-new/cotton-weed/train/labels'  # yolo格式标签所在文件夹
img_pathDir = '/home/rendoudou/datasets/yolo2coco-new/cotton-weed/train/images'  # 图片所在文件夹

with open(yolo_format_classes_path, 'r') as fr:  # 打开并读取类别文件
    lines1 = fr.readlines()
# print(lines1)
categories = []  # 存储类别的列表
for j, label in enumerate(lines1):
    label = label.strip()
    categories.append({'id': j + 1, 'name': label, 'supercategory': 'None'})  # 将类别信息添加到categories中
# print(categories)

write_json_context = dict()  # 写入.json文件的大字典
write_json_context['info'] = {'description': '', 'url': '', 'version': '', 'year': 2023, 'contributor': 'JeJe',
                              'date_created': '2023-05-18'}
write_json_context['licenses'] = [{'id': 1, 'name': None, 'url': None}]
write_json_context['categories'] = categories
write_json_context['images'] = []
write_json_context['annotations'] = []

# 接下来的代码主要添加'images'和'annotations'的key值
imageFileList = os.listdir(img_pathDir)  # 遍历该文件夹下的所有文件,并将所有文件名添加到列表中
count = 0
for i, imageFile in enumerate(imageFileList):



    imagePath = os.path.join(img_pathDir, imageFile)  # 获取图片的绝对路径
    # print(imagePath)
    # image = Image.open(imagePath)  # 读取图片,然后获取图片的宽和高
    try:
        image = Image.open(imagePath)
    except Exception as e:
        print(f"读取图像时出错: {e}")
    W, H = image.size

    img_context = {}  # 使用一个字典存储该图片信息
    # img_name=os.path.basename(imagePath)                                       #返回path最后的文件名。如果path以/或\结尾,那么就会返回空值
    img_context['file_name'] = imageFile
    img_context['height'] = H
    img_context['width'] = W
    img_context['date_captured'] = '2022-07-8'
    img_context['id'] = i  # 该图片的id
    img_context['license'] = 1
    img_context['color_url'] = ''
    img_context['flickr_url'] = ''
    write_json_context['images'].append(img_context)  # 将该图片信息添加到'image'列表中

    if imageFile[-4:] == 'jpeg':
        # print("jpeg文件")
        # count = count + 1

        txtFile = imageFile.replace('.jpeg', '.txt')  # 获取该图片获取的txt文件

    else:

        txtFile = imageFile.replace('.jpg', '.txt')  # 获取该图片获取的txt文件



    #       continue
    with open(os.path.join(yolo_format_annotation_path, txtFile), 'r') as fr:

        lines = fr.readlines()  # 读取txt文件的每一行数据,lines2是一个列表,包含了一个图片的所有标注信息
        count = count + 1
    for j, line in enumerate(lines):
        bbox_dict = {}  # 将每一个bounding box信息存储在该字典中
        # line = line.strip().split()
        # print(line.strip().split(' '))

        class_id, x, y, w, h = line.strip().split(' ')  # 获取每一个标注框的详细信息
        class_id, x, y, w, h = int(class_id), float(x), float(y), float(w), float(h)  # 将字符串类型转为可计算的int和float类型

        xmin = (x - w / 2) * W  # 坐标转换
        ymin = (y - h / 2) * H
        xmax = (x + w / 2) * W
        ymax = (y + h / 2) * H
        w = w * W
        h = h * H

        bbox_dict['id'] = i * 10000 + j  # bounding box的坐标信息
        bbox_dict['image_id'] = i
        bbox_dict['category_id'] = class_id + 1  # 注意目标类别要加一
        bbox_dict['iscrowd'] = 0
        height, width = abs(ymax - ymin), abs(xmax - xmin)
        bbox_dict['area'] = height * width
        bbox_dict['bbox'] = [xmin, ymin, w, h]
        bbox_dict['segmentation'] = [[xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax]]
        write_json_context['annotations'].append(bbox_dict)  # 将每一个由字典存储的bounding box信息添加到'annotations'列表中
print(count)
name = os.path.join(coco_format_save_path, "train" + '.json')  # 生成json文件的名字
with open(name, 'w') as fw:  # 将字典信息写入.json文件中
    json.dump(write_json_context, fw, indent=2)

YOLO格式数据换为COCO格式需要进行以下步骤: 1. 首先,需要了解YOLO格式COCO格式数据结构。YOLO格式包括图像路径、图像中物体的类别、位置和尺寸等信息;而COCO格式包括图像ID、宽度、高度、物体类别、位置、尺寸和分割等信息。 2. 然后,需要编写Python脚本来读取YOLO格式数据,并将其换为COCO格式。可以使用Python中的json库来创建COCO格式的JSON文件。 3. 在脚本中,需要定义一个字典来存储COCO格式数据。该字典包括以下键值对: - "images":包括图像ID、宽度和高度; - "annotations":包括物体类别、位置、尺寸和分割; - "categories":包括物体类别名称和ID。 4. 接下来,需要遍历YOLO格式数据,将其换为COCO格式,并将其添加到上述字典中。可以使用Python中的os库来获取图像路径和文件名。 5. 最后,将COCO格式的字典保存为JSON文件。 下面是一个简单的示例代码,可以将YOLO格式数据换为COCO格式: ``` import os import json # define categories categories = [{"id": 1, "name": "cat"}, {"id": 2, "name": "dog"}] # initialize COCO format dictionary coco_data = {"images": [], "annotations": [], "categories": categories} # read YOLO format data with open("yolo_data.txt") as f: yolo_data = f.readlines() # convert YOLO format data to COCO format for line in yolo_data: img_path, class_id, x, y, w, h = line.strip().split() img_id = int(os.path.splitext(os.path.basename(img_path))[0]) # add image data img_data = {"id": img_id, "width": w, "height": h} coco_data["images"].append(img_data) # add annotation data ann_data = {"image_id": img_id, "category_id": int(class_id), "bbox": [x, y, w, h]} coco_data["annotations"].append(ann_data) # save COCO format data to JSON file with open("coco_data.json", "w") as f: json.dump(coco_data, f) ``` 上述代码中,假设YOLO格式数据存储在yolo_data.txt文件中,每行包括图像路径、类别ID、位置和尺寸。其中,图像路径应该是相对路径,相对于代码所在的目录。类别ID应该是整数,且从1开始。位置和尺寸应该是归一化坐标,即相对于图像宽度和高度的比例。最终,将COCO格式数据保存为coco_data.json文件。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

毕竟是shy哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值