当前位置: 首页 > news >正文

Json转txt

1.多边形

import json
import os#将坐标归一化到 [0, 1] 范围。
def normalize_points(points, image_width, image_height):"""Normalize polygon points to be in the range [0, 1]."""return [(x / image_width, y / image_height) for x, y in points]#将Labelme JSON标注转换为TXT格式
def labelme_json_to_txt(json_dir, txt_dir):if not os.path.exists(txt_dir):os.makedirs(txt_dir)for filename in os.listdir(json_dir):if filename.endswith('.json'):json_file_path = os.path.join(json_dir, filename)image_name = os.path.splitext(filename)[0]txt_file_path = os.path.join(txt_dir, f'{image_name}.txt')with open(json_file_path, 'r', encoding='utf-8') as json_file:data = json.load(json_file)shapes = data.get('shapes', [])image_height = data.get('imageHeight', 0)image_width = data.get('imageWidth', 0)with open(txt_file_path, 'w', encoding='utf-8') as out_f:for shape in shapes:shape_type = shape.get('shape_type', '')label = shape.get('label', '')points = shape.get('points', [])if shape['shape_type'] == "polygon":normalized_points = normalize_points(points, image_width, image_height)# Write the label (if present) followed by normalized pointsout_f.write(f"{label}   ")out_f.write(" ".join(f"{x:.6f} {y:.6f}" for x, y in normalized_points))out_f.write("\n")else:print(f'Warning: Unknown shape type "{shape_type}" found in {json_file_path}')# 使用示例
json_directory = 'C:\\Users\Administrator\Desktop\自己制作的数据集\json'#你要修改的输入json地址
txt_output_directory = 'C:\\Users\Administrator\Desktop\自己制作的数据集\labels'#你要修改的txt保存的地址labelme_json_to_txt(json_directory, txt_output_directory)

2.矩形或者多边形

import os
import cv2
import glob
import json
import numpy as np
from tqdm import tqdm# 参考链接 https://zhuanlan.zhihu.com/p/622246547# 将labelme_json标注转yolo_txt
def convert(size, box):"""convert [xmin, xmax, ymin, ymax] to [x_centre, y_centre, w, h]"""dw = 1. / size[0]dh = 1. / size[1]x = (box[0] + box[1]) / 2.0y = (box[2] + box[3]) / 2.0w = box[1] - box[0]h = box[3] - box[2]x = x * dww = w * dwy = y * dhh = h * dhreturn [x, y, w, h]if __name__ == "__main__":class_names = []# json文件夹路径json_dir = r"O:\DeepLearningTool\01_handle_dataset\dataset\object\image"# 转化后txt的保存路径txt_dir = r"O:\DeepLearningTool\01_handle_dataset\dataset\object\label"if not os.path.exists(txt_dir):os.makedirs(txt_dir, exist_ok=True)json_pths = glob.glob(json_dir + "/*.json")for json_pth in tqdm(json_pths,  desc='Processing'):f1 = open(json_pth, "r")json_data = json.load(f1)img_pth = os.path.join(json_dir, json_pth.replace("json", "jpg"))img = cv2.imread(img_pth)h, w = img.shape[:2]tag = os.path.basename(json_pth)out_file = open(os.path.join(txt_dir, tag.replace("json", "txt")), "w")label_infos = json_data["shapes"]for label_info in label_infos:label = label_info["label"]points = label_info["points"]if len(points) >= 3:points = np.array(points)xmin, xmax = max(0, min(np.unique(points[:, 0]))), min(w, max(np.unique(points[:, 0])))ymin, ymax = max(0, min(np.unique(points[:, 1]))), min(h, max(np.unique(points[:, 1])))elif len(points) == 2:x1, y1 = points[0]x2, y2 = points[1]xmin, xmax = min(x1, x2), max(x1, x2)ymin, ymax = min(y1, y2), max(y1, y2)else:continuebbox = [xmin, xmax, ymin, ymax]bbox_ = convert((w,h), bbox)if label not in class_names:class_names.append(label)cls_id = class_names.index(label)out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bbox_]) + '\n')with open(txt_dir + 'classes.txt', 'w') as f:for i in class_names:f.write(i + '\n')

3.圆形/矩形/多边形

import os
import json
import warnings
warnings.filterwarnings("ignore")json_dir = './labels_json/'   # 输入 JSON
out_dir  = './labels_txt/'    # 输出 txtos.makedirs(out_dir, exist_ok=True)# 类别顺序,决定 cls_id
name = ['cola', 'pepsi', 'sprite', 'fanta', 'spring','ice', 'scream', 'milk', 'red', 'king']
name_class = {n: i for i, n in enumerate(name)}image_width  = 5568
image_height = 3712def json2txt(json_file, filename):with open(json_file, 'r', encoding='utf-8') as f:data = json.load(f)txt_path = os.path.join(out_dir, filename + '.txt')# 先清空open(txt_path, 'w').close()for shape in data.get('shapes', []):label = shape['label']if label not in name_class:continuecls_id = name_class[label]pts = shape['points']shape_type = shape.get('shape_type', '')# ===== 1) 圆形 =====if shape_type == 'circle' and len(pts) == 2:cx, cy = pts[0]px, py = pts[1]r = ((px - cx) ** 2 + (py - cy) ** 2) ** 0.5xmin, xmax = cx - r, cx + rymin, ymax = cy - r, cy + r# ===== 2) 矩形 / 多边形 =====else:# 统一取外接矩形xs, ys = zip(*pts)xmin, xmax = min(xs), max(xs)ymin, ymax = min(ys), max(ys)# 限制在图像内xmin = max(0, xmin)ymin = max(0, ymin)xmax = min(image_width,  xmax)ymax = min(image_height, ymax)# 中心点 + 宽高 归一化x = (xmin + xmax) / 2.0 / image_widthy = (ymin + ymax) / 2.0 / image_heightw = (xmax - xmin) / image_widthh = (ymax - ymin) / image_heightline = f"{cls_id} {x:.6f} {y:.6f} {w:.6f} {h:.6f}\n"with open(txt_path, 'a', encoding='utf-8') as f:f.write(line)def main():for file in os.listdir(json_dir):if file.endswith('.json'):json_path = os.path.join(json_dir, file)name_no_ext = os.path.splitext(file)[0]json2txt(json_path, name_no_ext)if __name__ == '__main__':main()

http://www.dtcms.com/a/340641.html

相关文章:

  • CTFshow系列——命令执行web38-40
  • 五种算法详解(SVM / Logistic Regression / kNN / Random Forest / HistGradientBoosting)
  • 无人机抗噪模块技术概述!
  • 20.web api 11
  • C5.6:双电源发射极偏置、特殊类偏置、PNP型偏置电路
  • 如何快速上手【Spring AOP】?核心应用实战(上篇)
  • 【买机器人,上BFT】香港大学联合项目论文解读 |Bunny-VisionPro:用于模仿学习的低成本实时双臂灵巧遥操作系统
  • SpringBoot 整合 Langchain4j RAG 技术深度使用解析
  • uv,下一代Python包管理工具
  • 机器学习-数据预处理全指南:从缺失值到特征编码
  • Tdesign-React 组件 Card 实现头部固定,内容区单独可滚动
  • vue:vue中的ref和reactive
  • 0820 SQlite与c语言的结合
  • 宿主机与容器通过 rmw_cyclonedds_cpp中间件进行ros2结点之间的通讯的相关注意事项
  • 开源的实时 Web 日志分析器GoAccess安装使用指南
  • 10X Visium HD空转流程1·Space Ranger v4.0.1的使用
  • [机器学习]11-基于CART决策树算法的西瓜数据集分类
  • bun + vite7 的结合,孕育的 Robot Admin 【靓仔出道】(十五)
  • LangGraph从入门到精通(二)——条件边与循环流程实现工具调用
  • 短剧小程序系统开发:构建影视娱乐新生态的基石
  • c#,装箱拆箱知识点示例理解
  • (Arxiv-2025)SkyReels-A2:在视频扩散变换器中组合任意内容
  • 分享智能解译算法获取及调用之建筑物提取
  • Ubuntu 虚拟显示器自动控制服务设置(有无显示器的切换)
  • pip 安装常见错误及实例化解决办法大全
  • 计算机网络技术学习-day4《路由器配置》
  • ubuntu下安装vivado2015.2时报错解决方法
  • SPI 机制深度剖析:Java、Spring、Dubbo 的服务发现哲学与实战指南
  • 根据Wireshark捕获数据包时间和长度绘制路由器发送给电脑数据的信号波形
  • 【FreeRTOS】临界资源管理