Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

to coco #2095

Open
JiyueWang opened this issue Nov 4, 2024 · 4 comments
Open

to coco #2095

JiyueWang opened this issue Nov 4, 2024 · 4 comments

Comments

@JiyueWang
Copy link

import os
import json
import glob
import torch

文件夹路径和输出JSON路径

txt_folder = 'runs\detect\exp5\labels' # 读取YOLO格式结果的文件夹路径
output_json = 'runs\detect\exp5\labelscoco_format.json' # 输出COCO格式JSON文件路径

def yolo_to_coco_bbox(bbox, img_width=1, img_height=1):
"""
将 YOLO 坐标转换为 COCO 坐标。
YOLO 格式: (center_x, center_y, width, height) -> COCO 格式: (x_min, y_min, width, height)
"""
x_c, y_c, w, h = bbox
x_min = (x_c - w / 2) * img_width
y_min = (y_c - h / 2) * img_height
width = w * img_width
height = h * img_height
return [x_min, y_min, width, height]

def convert_yolo_to_coco(txt_folder):
"""
读取 YOLO 格式的 txt 文件并转换为 COCO 格式。
"""
coco_results = []
txt_files = glob.glob(os.path.join(txt_folder, "*.txt"))

for txt_file in txt_files:
    image_id = int(os.path.splitext(os.path.basename(txt_file))[0])  # 使用文件名作为 image_id

    with open(txt_file, "r") as f:
        for line in f:
            line = line.strip().split()
            if len(line) < 5:
                continue  # 跳过无效行
            cls, x_center, y_center, width, height = map(float, line[:5])
            conf = float(line[5]) if len(line) > 5 else 1.0  # 默认置信度为1.0(如果没有提供)

            # 转换YOLO边界框坐标为COCO格式
            bbox = yolo_to_coco_bbox([x_center, y_center, width, height])

            # 构建COCO格式的字典
            coco_results.append({
                "image_id": image_id,
                "category_id": int(cls),
                "bbox": bbox,
                "score": conf
            })

return coco_results

转换YOLO结果并保存为COCO格式的JSON

coco_results = convert_yolo_to_coco(txt_folder)
with open(output_json, "w") as f:
json.dump(coco_results, f, indent=4)

print(f"COCO format results saved to {output_json}")

@JiyueWang
Copy link
Author

dear junjun

@JiyueWang
Copy link
Author

在detect()函数中

output_file = 'results.txt' # 设定单一输出文件路径

在循环外打开文件,确保是追加模式

with open(output_file, 'a') as f:
for path, img, im0s, vid_cap in dataset:
# 检测处理代码...
for *xyxy, conf, cls in reversed(det):
if save_txt: # 将结果写入到单一的文件
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # 归一化坐标
line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # 标签格式
f.write(('%g ' * len(line)).rstrip() % line + '\n')

import os

输入文件夹路径(包含多个YOLO格式的结果文件)

input_folder = 'path/to/yolo/results'

输出合并的单一结果文件路径

output_file = 'combined_results.txt'

def combine_yolo_results(input_folder, output_file):
with open(output_file, 'w') as outfile:
# 遍历输入文件夹中的每个文件
for filename in os.listdir(input_folder):
if filename.endswith('.txt'):
# 获取图片ID(从文件名中去掉扩展名)
image_id = os.path.splitext(filename)[0]

            # 读取每个YOLO格式的文件
            with open(os.path.join(input_folder, filename), 'r') as infile:
                for line in infile:
                    # 每行数据:class_id x_center y_center width height
                    # 添加image_id列,并写入到输出文件
                    outfile.write(f"{image_id} {line.strip()}\n")

print(f"合并结果已保存至: {output_file}")

运行合并函数

combine_yolo_results(input_folder, output_file)

@JiyueWang
Copy link
Author

junjun 听到请回答

@joe-joe-shen
Copy link

dear junjun

1111

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants