图像标签格式转换

在做图像检测的时候,不同打标签软件得到的标签格式可能会不一样,此处提供lableimg(txt格式)和lableme(json格式)的互换。

json →txt

import os
import json
import cv2
import base64
import argparsedef parse_opt():parser = argparse.ArgumentParser()# 根据你的路径进行修改parser.add_argument('--img_path', type=str, default='img/')parser.add_argument('--txt_path', type=str, default='labels/test.txt')parser.add_argument('--json_path', type=str, default='json/')parser.add_argument('--class_names', type=str, default='[your class name]') # 修改为你的类别名称opt = parser.parse_args()return optdef decode_txt_file(txt_path, img_path, json_path, class_names):class_name = {i: name for i, name in enumerate(class_names)}dic = {}dic['version'] = '5.0.2'dic['flags'] = {}dic['shapes'] = []img_name = os.path.basename(txt_path).replace('.txt', '.jpg')img = cv2.imread(os.path.join(img_path, img_name))imageHeight, imageWidth, _ = img.shapewith open(txt_path) as f:datas = f.readlines()for data in datas:shape = {}data = data.strip().split(' ')class_id = int(data[0])shape['label'] = class_name[class_id]x = float(data[1]) * imageWidthy = float(data[2]) * imageHeightw = float(data[3]) * imageWidthh = float(data[4]) * imageHeightx1 = x - w / 2y1 = y - h / 2x2 = x1 + wy2 = y1 + hshape['points'] = [[x1, y1], [x2, y2]]shape['shape_type'] = 'rectangle'shape['flags'] = {}dic['shapes'].append(shape)dic['imagePath'] = img_namedic['imageData'] = base64.b64encode(open(os.path.join(img_path, img_name), 'rb').read()).decode('utf-8')dic['imageHeight'] = imageHeightdic['imageWidth'] = imageWidthjson_file = os.path.join(json_path, os.path.basename(txt_path).replace('.txt', '.json'))with open(json_file, 'w') as fw:json.dump(dic, fw)print(f'Saved {json_file}.')if __name__ == '__main__':opt = parse_opt()img_path = opt.img_pathtxt_path = opt.txt_pathjson_path = opt.json_pathclass_names = opt.class_names.split(',')if txt_path.endswith('.txt'):  # 单个文件转换decode_txt_file(txt_path, img_path, json_path, class_names)print('The conversion of single txt to json is complete')else:txt_names = os.listdir(txt_path)  # 多个文件转换for txt_name in txt_names:txt_file = os.path.join(txt_path, txt_name)decode_txt_file(txt_file, img_path, json_path, class_names)print('The conversion of txt to json is complete')

txt → json

import os
import json
import cv2
import base64
import argparsedef parse_opt():# Parse command line arguments.parser = argparse.ArgumentParser()parser.add_argument('--img_path', type=str, default='img/')parser.add_argument('--txt_path', type=str, default='labels')parser.add_argument('--json_path', type=str, default='json/')parser.add_argument('--class_names', type=str, default='[your class name]') # 修改为你的类别名称opt = parser.parse_args()return optdef decode_txt_file(txt_path, img_path, json_path, class_names):# Convert a txt file to a json file.class_name = {i: name for i, name in enumerate(class_names)}dic = {}dic['version'] = '5.0.2'dic['flags'] = {}dic['shapes'] = []img_name = os.path.basename(txt_path).replace('.txt', '.jpg')img = cv2.imread(os.path.join(img_path, img_name))imageHeight, imageWidth, _ = img.shapewith open(txt_path) as f:datas = f.readlines()for data in datas:shape = {}data = data.strip().split(' ')class_id = int(data[0])shape['label'] = class_name[class_id]x = float(data[1]) * imageWidthy = float(data[2]) * imageHeightw = float(data[3]) * imageWidthh = float(data[4]) * imageHeightx1 = x - w / 2y1 = y - h / 2x2 = x1 + wy2 = y1 + hshape['points'] = [[x1, y1], [x2, y2]]shape['shape_type'] = 'rectangle'shape['flags'] = {}dic['shapes'].append(shape)dic['imagePath'] = img_namedic['imageData'] = base64.b64encode(open(os.path.join(img_path, img_name), 'rb').read()).decode('utf-8')dic['imageHeight'] = imageHeightdic['imageWidth'] = imageWidthjson_file = os.path.join(json_path, os.path.basename(txt_path).replace('.txt', '.json'))with open(json_file, 'w') as fw:json.dump(dic, fw)print(f'Saved {json_file}.')def convert(img_size, box):# Convert absolute coordinates to relative coordinates.dw = 1. / (img_size[0])dh = 1. / (img_size[1])x = (box[0] + box[2]) / 2.0 - 1y = (box[1] + box[3]) / 2.0 - 1w = box[2] - box[0]h = box[3] - box[1]x = x * dww = w * dwy = y * dhh = h * dhreturn (x, y, w, h)def decode_json(json_path, json_name, txt_path):# Convert a json file to a txt file.class_name = {name: i for i, name in enumerate(class_names)}txt_file = open(os.path.join(txt_path, json_name[0:-5] + '.txt'), 'w')json_path = os.path.join(json_path, json_name)data = json.load(open(json_path, 'r', encoding='gb2312', errors='ignore'))img_w = data['imageWidth']img_h = data['imageHeight']for i in data['shapes']:label_name = i['label']if (i['shape_type'] == 'rectangle'):x1 = int(i['points'][0][0])y1 = int(i['points'][0][1])x2 = int(i['points'][1][0])y2 = int(i['points'][1][1])bb = (x1, y1, x2, y2)bbox = convert((img_w, img_h), bb)txt_file.write(str(class_name[label_name]) + " " + " ".join([str(a) for a in bbox]) + '\n')print(f"Saved{json_name[0:-5] + '.txt'}")txt_file.close()if __name__ == '__main__':opt = parse_opt()img_path = opt.img_pathtxt_path = opt.txt_pathjson_path = opt.json_pathclass_names = opt.class_names.split(',')# Convert txt files to json files.if txt_path.endswith('.txt'):decode_txt_file(txt_path, img_path, json_path, class_names)print('The conversion of single txt to json is complete')else:txt_names = os.listdir(txt_path)for txt_name in txt_names:txt_file = os.path.join(txt_path, txt_name)decode_txt_file(txt_file, img_path, json_path, class_names)print('The conversion of txt to json is complete')

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/62082.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【机器学习】——朴素贝叶斯模型

💻博主现有专栏: C51单片机(STC89C516),c语言,c,离散数学,算法设计与分析,数据结构,Python,Java基础,MySQL,linux&#xf…

CMake Qt Debug/Release可执行文件增加图标

将logo.ico复制到CMakeLists.txt的同级目录下,然后新建logo.rc文件,里边输入如下代码 IDI_ICON1 ICON DISCARDABLE "logo.ico"CMakeLists.txt修改此处 ADD_EXECUTABLE(${ModuleName} ${KIT_SRCS} ${QRC_SRCS} ${UISrcs} ${MOC_OUTPUT} logo.…

【Android+多线程】异步 多线程 知识总结:基础概念 / 多种方式 / 实现方法 / 源码分析

1 基本概念 1.1 线程 定义:一个基本的CPU执行单元 & 程序执行流的最小单元 比进程更小的可独立运行的基本单位,可理解为:轻量级进程组成:线程ID 程序计数器 寄存器集合 堆栈注:线程自己不拥有系统资源&#…

自动驾驶系统研发系列—智能驾驶倒车盲区终结者:智能侧向警告与制动技术解析

🌟🌟 欢迎来到我的技术小筑,一个专为技术探索者打造的交流空间。在这里,我们不仅分享代码的智慧,还探讨技术的深度与广度。无论您是资深开发者还是技术新手,这里都有一片属于您的天空。让我们在知识的海洋中一起航行,共同成长,探索技术的无限可能。 🚀 探索专栏:学…

Error: Invalid version flag: if 问题排查

问题描述: 国产化系统适配,arm架构的centos 在上面运行docker 启动后需要安装数据库 依赖perl 在yum install -y perl 时提示: “Error: Invalid version flag: if”

Git指令大全

文章目录 前言1. 初始化与配置初始化一个 Git 仓库设置 Git 用户名设置 Git 邮箱查看当前配置 2. 版本管理查看版本历史查看简洁的版本历史查看某个文件的修改历史查看文件的更改查看暂存区与工作区的区别 3. 分支管理创建新分支切换分支创建并切换到新分支查看所有分支删除本地…

华为鸿蒙内核成为HarmonyOS NEXT流畅安全新基座

HDC2024华为重磅发布全自研操作系统内核—鸿蒙内核,鸿蒙内核替换Linux内核成为HarmonyOS NEXT稳定流畅新基座。鸿蒙内核具备更弹性、更流畅、更安全三大特征,性能超越Linux内核10.7%。 鸿蒙内核更弹性:元OS架构,性能安全双收益 万…

《免费学习网站推荐1》

《免费学习网站推荐1》 1、综合学习类 网易公开课:有国内众多大学视频公开课,以及TED、可汗学院等国际名校公开课,课程涵盖文学、哲学、语言、社会、历史、商业等多个领域,外文课程有翻译可无障碍观看.Coursera:与全…

五种创建k8s的configMap的方式及configmap使用

configmap介绍 Kubernetes 提供了 ConfigMap 来管理应用配置数据,将配置信息从容器镜像中解耦,使应用更灵活、可移植。 1、基于一个目录来创建ConfigMap ​ 你可以使用 kubectl create configmap 基于同一目录中的多个文件创建 ConfigMap。 当你基于目…

CTF之密码学(凯撒加密)

一、基本原理 凯撒加密是一种替换加密的技术,明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。例如,当偏移量是3的时候,所有的字母A将被替换成D,B变成E,以此类推。这个加密方法是以罗马共和时期凯撒的名字命名的,据说凯撒曾用此方法…

解决数据库sql_mode=only_full_group_by配置问题

当数据库配置sql_modeonly_full_group_by时,sql查询时用到group by且查询字段没有全部出现在group by后,会出现sql错误: Caused by: java.sql.SQLSyntaxErrorException: Expression #2 of SELECT list is not in GROUP BY clause and contai…

如何将本地项目上传到gitee上

本地项目代码想上传到gitee管理、使用idea编辑器操作上传 新建仓库、填写信息 创建好了仓库,把HTTPS路径复制一下,之后会用到。 用命令进入项目进行git初始化 执行命令: cd 文件夹 git init 用idea把项目打开,然后配置一下gi…

goframe开发一个企业网站 MongoDB 完整工具包18

1. MongoDB 工具包完整实现 (mongodb.go) package mongodbimport ("context""fmt""time""github.com/gogf/gf/v2/frame/g""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options" )va…

大型语言模型LLM - Finetuning vs Prompting

资料来自台湾大学李宏毅教授机器学课程ML 2023 Spring,如有侵权请通知下架 台大机器学课程ML 2023 Springhttps://speech.ee.ntu.edu.tw/~hylee/ml/2023-spring.php2023/3/10 课程 機器如何生成文句 内容概要 主要探讨了大型语言模型的两种不同期待及其导致的两类…

Scikit-learn Pipeline完全指南:高效构建机器学习工作流

在机器学习工作流程中,组合估计器通过将多个转换器(Transformer)和预测器(Predictor)整合到一个管道(Pipeline)中,可以有效简化整个过程。这种方法不仅简化了数据预处理环节,还能确保处理过程的一致性,最大限度地降低数据泄露的风险。构建组合估计器最常用的工具是Scikit-learn…

kali Linux中foremost安装

记录一下 foremost工具介绍 foremost是基于文件开始格式,文件结束标志和内部数据结构进行恢复文件的程序。该工具通过分析不同类型文件的头、尾和内部数据结构,同镜像文件的数据进行比对,以还原文件。它默认支持19种类型文件的恢复。用户还可…

ChatGPT如何辅助academic writing?

今天想和大家分享一篇来自《Nature》杂志的文章《Three ways ChatGPT helps me in my academic writing》,如果您的日常涉及到学术论文的写作(writing)、编辑(editing)或者审稿( peer review)&a…

2024年11月26日Github流行趋势

项目名称:v2rayN 项目维护者:2dust yfdyh000 CGQAQ ShiinaRinne Lemonawa 项目介绍:一个支持Xray核心及其他功能的Windows和Linux图形用户界面客户端。 项目star数:70,383 项目fork数:11,602 项目名称:fre…

Zookeeper实现分布式锁、Zookeeper实现配置中心

一、Zookeeper实现分布式锁 分布式锁主要用于在分布式环境中保证数据的一致性。 包括跨进程、跨机器、跨网络导致共享资源不一致的问题。 1.Zookeeper分布式锁的代码实现 新建一个maven项目ZK-Demo,然后在pom.xml里面引入相关的依赖 <dependency><groupId>com.…

大数据面试SQL题-笔记02【查询、连接、聚合函数】

大数据面试SQL题复习思路一网打尽&#xff01;(文档见评论区)_哔哩哔哩_bilibiliHive SQL 大厂必考常用窗口函数及相关面试题 大数据面试SQL题-笔记01【运算符、条件查询、语法顺序、表连接】大数据面试SQL题-笔记02【查询、连接、聚合函数】​​​​​​​ 目录 01、查询 01…