将提取InterHand2.6M中的bbox转YOLO格式

import os
import json
import cv2

def coco_to_yolo_bbox(coco_bbox, img_width, img_height):
    x1, y1, x2, y2 = coco_bbox
    x_center = (x1 + x2) / 2.0
    y_center = (y1 + y2) / 2.0
    width = x2 - x1
    height = y2 - y1

    # 归一化
    x_center /= img_width
    y_center /= img_height
    width /= img_width
    height /= img_height

    return [x_center, y_center, width, height]

json_folder = ""
img_folder = ""
output_folder = ""

if not os.path.exists(output_folder):
    os.makedirs(output_folder)

json_files = [os.path.join(json_folder, f) for f in os.listdir(json_folder) if f.endswith(".json")]

for json_file in json_files:
    with open(json_file, 'r') as f:
        data = json.load(f)
    bbox = data.get("bbox", [])

    img_path = os.path.join(img_folder, os.path.splitext(os.path.basename(json_file))[0] + ".jpg")
    img = cv2.imread(img_path)
    img_height, img_width = img.shape[:2]

    yolo_bbox = coco_to_yolo_bbox(bbox, img_width, img_height)
    yolo_format = f"2 {' '.join(map(str, yolo_bbox))}\n"

    output_file_path = os.path.join(output_folder, os.path.splitext(os.path.basename(json_file))[0] + ".txt")
    with open(output_file_path, 'w') as f:
        f.write(yolo_format)

        这段代码的功能是将 COCO 格式的边界框转换为 YOLO 格式的边界框,并将其保存为 txt 文件。首先,代码定义了一个名为 coco_to_yolo_bbox 的函数,用于将 COCO 格式的边界框转换为 YOLO 格式的边界框。其中,coco_bbox 表示 COCO 格式的边界框列表,img_widthimg_height 分别表示图像的宽度和高度。函数计算出 YOLO 格式的边界框后,将其以列表形式返回。然后,代码定义了三个变量,分别是 JSON 文件夹路径、图像文件夹路径和输出文件夹路径,并检查输出文件夹是否存在。接下来,代码生成 JSON 文件夹中所有以 .json 结尾的文件的文件路径,并循环遍历每个 JSON 文件。在循环中,代码使用 json.load() 函数读取 JSON 文件中的数据,并提取边界框信息。然后,代码根据图像文件路径读取图像,并获取其宽度和高度。接着,代码调用 coco_to_yolo_bbox() 函数将 COCO 格式的边界框转换为 YOLO 格式的边界框,并将其格式化为 YOLO 格式的字符串。最后,代码将 YOLO 格式的字符串保存为 .txt 文件,文件名与对应的图像文件名相同,只是扩展名不同。总的来说,这段代码主要是用于 COCO 格式与 YOLO 格式边界框格式之间的转换,并将转换后的结果保存为 .txt 文件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

没了海绵宝宝的派大星

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

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

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

打赏作者

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

抵扣说明:

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

余额充值