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

news/2024/7/24 12:12:46 标签: 目标检测, YOLO, 人工智能, 计算机视觉

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


文章目录

  • 常用目标检测的格式转换脚本文件txt,json等
  • 前言
  • 一、json格式转yolo的txt格式
  • 二、yolov8的关键点labelme打的标签json格式转可训练的txt格式
  • 三、yolo的目标检测txt格式转coco数据集标签的json格式
  • 四、根据yolo的目标检测训练的最好权重推理图片
  • 五、根据yolo标签的txt文件提取某一个特征类别的标签, 并在原图上进行绘制
  • 六、根据yolo标签的txt文件提取某一个特征类别的标签, 并在原图上进行绘制


前言

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

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


一、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"

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

相关文章

Prompt Engineering overview

文章目录 High level look迭代法优化iterate参考 High level look 提示的重要性往往会被低估或者高估 低估是因为正确的提示技术如果使用得当,可以让我们走的更远。 高估是因为基于提示的应用程序,需要围绕提示进行大量的工程设计才能运行良好。 提示工…

Axure第12享:Google加载Axure扩展程序

1、需求描述 在双击打开RP文件进行预览时,提示要为Google浏览器加载Extension(扩展程序),如下图所示。 2、解决思路 按照系统指导的操作步骤,但要注意1点,加载“扩展程序”时是选择整个文件夹&#xff0c…

Hudi 写入流程(图)

前言 主要为之前总结的源码文章补充流程图。总结一下整体流程说明 之前以Java Client为例,总结了 Insert 源码的整体流程及部分源码,由于各种原因,没有总结完。长时间不看这方面的源码,容易忘记,之前没有总结流程图,现在回忆起来比较麻烦,不如看流程图方便快捷。所以先补…

Linux学习笔记(二)账户和组

一、基本概念 用 户:用户id,被称为UID 基本组:账户id,被称为GID。用户只能加一个基本组。 0代表超级管理员,root账号。 附加组:用户能加多个基本组。 二、添加账户和组 创建用户名tom,失效…

没什么事情,随记一下 -出差

前几天出差,因客户的需求,项目不能连接外网,也没有vpn,所以只能实地实施,对接接口,我其实也是第一次出差,也不知道出差需要注意什么,反正就是什么也不知道,然后就是硬着头…

02归并排序——分治递归

02_归并排序_——分治_递归_ #include <stdio.h>void merge(int arr[], int l, int m, int r) {int n1 m -l 1;int n2 r -m;//创建临时数组int L[n1], R[n2];for(int i 0; i < n1; i){L[i] arr[l i];}for(int j 0; j < n2; j){R[j] arr[m 1 j];}int i …

【python】PyQt5可视化开发,如何设计鼠标显示的形状?

✨✨ 欢迎大家来到景天科技苑✨✨ &#x1f388;&#x1f388; 养成好习惯&#xff0c;先赞后看哦~&#x1f388;&#x1f388; &#x1f3c6; 作者简介&#xff1a;景天科技苑 &#x1f3c6;《头衔》&#xff1a;大厂架构师&#xff0c;华为云开发者社区专家博主&#xff0c;…

ChatGPT 5.0:一年半后的展望与看法

在人工智能领域&#xff0c;每一次技术的飞跃都预示着未来生活与工作方式的深刻变革。随着OpenAI在人工智能领域的不断探索与突破&#xff0c;ChatGPT系列模型已成为全球关注的焦点。当谈及ChatGPT 5.0在未来一年半后可能发布的前景时&#xff0c;我们不禁充满期待&#xff0c;…