常用目标检测的格式转换脚本文件txt,json等

常用目标检测的格式转换脚本文件txt,json等



前言

⭐️ ⭐️ ⭐️ 还在完善中 ⭐️ ⭐️ ⭐️

本节主要介绍在目标检测领域内,常用的格式转换脚本


一、json格式转yolo的txt格式

json格式的目标检测数据集标签格式转yolo目标检测的标签txt的格式

代码如下(示例): 主要修改 classes, json_folder_path, output_dir

"""
目标检测的 json --> 转为 yolo的txt
"""
import json
import os


def convert(size, box):
    dw = 1. / size[0]
    dh = 1. / size[1]
    x = (box[0] + box[2]) / 2.0
    y = (box[1] + box[3]) / 2.0
    w = box[2] - box[0]
    h = box[3] - box[1]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh

    return (x, y, w, h)


def decode_json(json_path, output_dir, classes):
    with open(json_path, 'r', encoding='utf-8') as f:
        data = json.load(f)

    base_name = os.path.splitext(os.path.basename(data['imagePath']))[0]
    txt_path = os.path.join(output_dir, base_name + '.txt')
    with open(txt_path, 'w', encoding='utf-8') as txt_file:
        for shape in data['shapes']:
            if shape['shape_type'] == 'rectangle':
                label = shape['label']
                if label not in classes:
                    continue
                cls_id = classes.index(label)
                points = shape['points']
                x1, y1 = points[0]
                x2, y2 = points[1]  # Assuming the points are diagonal

                bb = convert((data['imageWidth'], data['imageHeight']), [x1, y1, x2, y2])
                txt_file.write(f"{
     cls_id} {
     ' '.join(map(str, bb))}\n")


if __name__ == "__main__":
    # 指定YOLO类别
    classes = ['loose', 'un-loose']  # 根据实际类别名称进行修改
    # JSON格式的标签文件路径
    json_folder_path = './json'  # 替换为实际的JSON文件夹路径
    # 转换为YOLO格式的TXT标签文件存储路径
    output_dir = './txt'  # 替换为实际的TXT保存路径

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

    json_files = [file for file in os.listdir(json_folder_path) if file.endswith('.json')]

    for json_file in json_files:
        json_path = os.path.join(json_folder_path, json_file)
        decode_json(json_path, output_dir, classes)

    # 将类别名称写入classes.txt文件
    with open(os.path.join(output_dir, 'classes.txt'), 'w', encoding='utf-8') as file:
        for class_name in classes:
            file.write(class_name + '\n')

    print(f"Conversion completed. TXT files are saved in {
     output_dir}")

二、yolov8的关键点labelme打的标签json格式转可训练的txt格式

yolov8的关键点labelme打的标签json格式转可训练的txt格式

代码如下(示例):只需修改 class_list, keypoint_list, img_list

将labelme标注关键点数据集的 json文件转为 yolo 格式
采用 labelme进行标注
"""
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
import glob
import json
import tqdm


# 物体类别
class_list = ["fks"]
# 关键点的顺序
keypoint_list = ["P1", "P2", "P3", "P4"]


def json_to_yolo(img_data, json_data):
    h, w = img_data.shape[:2]
    # 步骤:
    # 1. 找出所有的矩形,记录下矩形的坐标,以及对应group_id
    # 2. 遍历所有的head和tail,记下点的坐标,以及对应group_id,加入到对应的矩形中
    # 3. 转为yolo格式

    rectangles = {
   }
    # 遍历初始化
    for shape in json_data["shapes"]:
        label = shape["label"]              # pen, head, tail
        group_id = shape["group_id"]        # 0, 1, 2, ...
        points = shape["points"]            # x,y coordinates
        shape_type = shape["shape_type"]

        # 只处理矩形
        if shape_type == "rectangle":
            if group_id not in rectangles:
                rectangles[group_id] = {
   
                    "label": label,
                    "rect": points[0] + points[1],  # Rectangle [x1, y1, x2, y2]
                    "keypoints_list": []
                }
    # 遍历更新,将点加入对应group_id的矩形中
    for keypoint in keypoint_list:
        for shape in json_data["shapes"]:
            label = shape["label"]
            group_id = shape["group_id"]
            points = shape["points"]
            # 如果匹配到了对应的keypoint
            if label == keypoint:
                rectangles[group_id]["keypoints_list"

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-09 16:48:08       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-09 16:48:08       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-09 16:48:08       57 阅读
  4. Python语言-面向对象

    2024-07-09 16:48:08       68 阅读

热门阅读

  1. 信息收集-arping

    2024-07-09 16:48:08       24 阅读
  2. flutter如何实现点击一文字后 打开对应的超链接

    2024-07-09 16:48:08       24 阅读
  3. TCP协议是安全的吗?

    2024-07-09 16:48:08       50 阅读
  4. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-07-09 16:48:08       39 阅读
  5. 【Python教程】压缩PDF文件大小

    2024-07-09 16:48:08       48 阅读
  6. 通过文章id递归查询所有评论(xml)

    2024-07-09 16:48:08       55 阅读
  7. 金融行业:银行的三大类业务

    2024-07-09 16:48:08       44 阅读
  8. Vim和Nano简介

    2024-07-09 16:48:08       32 阅读
  9. 产品经理基础入门

    2024-07-09 16:48:08       37 阅读