1、将修改json指定位置的label值,并保持原样输出

import json
import osdef changeJsonLabelName(json_dir, new_json_dir):json_files = os.listdir(json_dir)json_dict = {}# 需要修改的新名称new_name1 = 'mubiao'for json_file in json_files:jsonfile = json_dir + '/' + json_filejson_out = new_json_dir + '/' + json_file# 读单个json文件with open(jsonfile, 'r', encoding='utf-8') as jf:info = json.load(jf)# print(type(info))# 找到位置进行修改for i, label in enumerate(info['shapes']):if label['label'] != "mubiao":label['label'] = new_name1# 使用新字典替换修改后的字典json_dict = info# set_trace()# 将替换后的内容写入原文件with open(json_out, 'w') as new_jf:json.dump(json_dict, new_jf, indent=2)print('change name over!')label_path = './tar'  # 原始标签文件夹
dst_path = './new_tar'  # 存储修改后标签的文件夹
changeJsonLabelName(label_path, dst_path)

2、将json转化为xml

# -*- coding: utf-8 -*-
import numpy as np
import json# 读取json 标签内容
# 当中有2种模式,一种rectangle,表示json文件是通过labelme的rectangle方式标注,
# 一种polygon,表示json文件是通过labelme的polygon方式标注。根据实际情况进行变换。
##### 1
class ReadAnno:def __init__(self, json_path, process_mode="rectangle"):self.json_data = json.load(open(json_path))self.filename = self.json_data['imagePath']self.width = self.json_data['imageWidth']self.height = self.json_data['imageHeight']self.coordis = []assert process_mode in ["rectangle", "polygon"]if process_mode == "rectangle":self.process_polygon_shapes()elif process_mode == "polygon":self.process_polygon_shapes()def process_rectangle_shapes(self):for single_shape in self.json_data['shapes']:bbox_class = single_shape['label']xmin = single_shape['points'][0][0]ymin = single_shape['points'][0][1]xmax = single_shape['points'][1][0]ymax = single_shape['points'][1][1]self.coordis.append([xmin, ymin, xmax, ymax, bbox_class])def process_polygon_shapes(self):for single_shape in self.json_data['shapes']:bbox_class = single_shape['label']temp_points = []for couple_point in single_shape['points']:x = float(couple_point[0])y = float(couple_point[1])temp_points.append([x, y])temp_points = np.array(temp_points)xmin, ymin = temp_points.min(axis=0)xmax, ymax = temp_points.max(axis=0)self.coordis.append([xmin, ymin, xmax, ymax, bbox_class])def get_width_height(self):return self.width, self.heightdef get_filename(self):return self.filenamedef get_coordis(self):return self.coordis##### 2
from xml.dom.minidom import Document#  创建labelimg标注格式的xml文件标签  并添加读取的数据,进行转换
class CreateAnno:def __init__(self, ):self.doc = Document()  # 创建DOM文档对象self.anno = self.doc.createElement('annotation')  # 创建根元素self.doc.appendChild(self.anno)self.add_folder()self.add_path()self.add_source()self.add_segmented()# self.add_filename()# self.add_pic_size(width_text_str=str(width), height_text_str=str(height), depth_text_str=str(depth))def add_folder(self, floder_text_str='JPEGImages'):floder = self.doc.createElement('floder')  ##建立自己的开头floder_text = self.doc.createTextNode(floder_text_str)  ##建立自己的文本信息floder.appendChild(floder_text)  ##自己的内容self.anno.appendChild(floder)def add_filename(self, filename_text_str='00000.jpg'):filename = self.doc.createElement('filename')filename_text = self.doc.createTextNode(filename_text_str)filename.appendChild(filename_text)self.anno.appendChild(filename)def add_path(self, path_text_str="None"):path = self.doc.createElement('path')path_text = self.doc.createTextNode(path_text_str)path.appendChild(path_text)self.anno.appendChild(path)def add_source(self, database_text_str="Unknow"):source = self.doc.createElement('source')database = self.doc.createElement('database')database_text = self.doc.createTextNode(database_text_str)  # 元素内容写入database.appendChild(database_text)source.appendChild(database)self.anno.appendChild(source)def add_pic_size(self, width_text_str="0", height_text_str="0", depth_text_str="3"):size = self.doc.createElement('size')width = self.doc.createElement('width')width_text = self.doc.createTextNode(width_text_str)  # 元素内容写入width.appendChild(width_text)size.appendChild(width)height = self.doc.createElement('height')height_text = self.doc.createTextNode(height_text_str)height.appendChild(height_text)size.appendChild(height)depth = self.doc.createElement('depth')depth_text = self.doc.createTextNode(depth_text_str)depth.appendChild(depth_text)size.appendChild(depth)self.anno.appendChild(size)def add_segmented(self, segmented_text_str="0"):segmented = self.doc.createElement('segmented')segmented_text = self.doc.createTextNode(segmented_text_str)segmented.appendChild(segmented_text)self.anno.appendChild(segmented)def add_object(self,name_text_str="None",xmin_text_str="0",ymin_text_str="0",xmax_text_str="0",ymax_text_str="0",pose_text_str="Unspecified",truncated_text_str="0",difficult_text_str="0"):object = self.doc.createElement('object')name = self.doc.createElement('name')name_text = self.doc.createTextNode(name_text_str)name.appendChild(name_text)object.appendChild(name)pose = self.doc.createElement('pose')pose_text = self.doc.createTextNode(pose_text_str)pose.appendChild(pose_text)object.appendChild(pose)truncated = self.doc.createElement('truncated')truncated_text = self.doc.createTextNode(truncated_text_str)truncated.appendChild(truncated_text)object.appendChild(truncated)difficult = self.doc.createElement('difficult')difficult_text = self.doc.createTextNode(difficult_text_str)difficult.appendChild(difficult_text)object.appendChild(difficult)bndbox = self.doc.createElement('bndbox')xmin = self.doc.createElement('xmin')xmin_text = self.doc.createTextNode(xmin_text_str)xmin.appendChild(xmin_text)bndbox.appendChild(xmin)ymin = self.doc.createElement('ymin')ymin_text = self.doc.createTextNode(ymin_text_str)ymin.appendChild(ymin_text)bndbox.appendChild(ymin)xmax = self.doc.createElement('xmax')xmax_text = self.doc.createTextNode(xmax_text_str)xmax.appendChild(xmax_text)bndbox.appendChild(xmax)ymax = self.doc.createElement('ymax')ymax_text = self.doc.createTextNode(ymax_text_str)ymax.appendChild(ymax_text)bndbox.appendChild(ymax)object.appendChild(bndbox)self.anno.appendChild(object)def get_anno(self):return self.annodef get_doc(self):return self.docdef save_doc(self, save_path):with open(save_path, "w") as f:self.doc.writexml(f, indent='\t', newl='\n', addindent='\t', encoding='utf-8')# 更改参数运行: json格式文件所在的文件夹,将要保存的xml文件夹,以及原数据的标注方式。
##### 3
import os
from tqdm import tqdm# from read_json_anno import ReadAnno
# from create_xml_anno import CreateAnnodef json_transform_xml(json_path, xml_path, process_mode="rectangle"):json_path = json_pathjson_anno = ReadAnno(json_path, process_mode=process_mode)width, height = json_anno.get_width_height()filename = json_anno.get_filename()coordis = json_anno.get_coordis()xml_anno = CreateAnno()xml_anno.add_filename(filename)xml_anno.add_pic_size(width_text_str=str(width), height_text_str=str(height), depth_text_str=str(3))for xmin, ymin, xmax, ymax, label in coordis:xml_anno.add_object(name_text_str=str(label),xmin_text_str=str(int(xmin)),ymin_text_str=str(int(ymin)),xmax_text_str=str(int(xmax)),ymax_text_str=str(int(ymax)))xml_anno.save_doc(xml_path)if __name__ == "__main__":root_json_dir = r"D:\Users\12778\Desktop\gu\new_tar"root_save_xml_dir = r"D:\Users\12778\Desktop\gu\xml"for json_filename in tqdm(os.listdir(root_json_dir)):json_path = os.path.join(root_json_dir, json_filename)save_xml_path = os.path.join(root_save_xml_dir, json_filename.replace(".json", ".xml"))json_transform_xml(json_path, save_xml_path, process_mode="rectangle")

3、将xml转化为txt

'''
将xml格式的标注文件转为yolo的txt格式
将.xml文件放至labels文件夹中,转换后的.txt文件会被放到labelsyolo文件夹中
根据目标类别修改1处
'''import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import joindef convert(size, box):dw = 1. / (size[0])dh = 1. / (size[1])x = (box[0] + box[1]) / 2.0 - 1y = (box[2] + box[3]) / 2.0 - 1w = box[1] - box[0]h = box[3] - box[2]x = x * dww = w * dwy = y * dhh = h * dhreturn (x, y, w, h)def convert_annotation(image_id):in_file = open('xml/%s.xml' % (image_id))  # 存储路径out_file = open('txt/%s.txt' % (image_id), 'w')tree = ET.parse(in_file)root = tree.getroot()# img_path = 'images/%s.jpg'%(image_id)# img = cv2.imread(img_path)size = root.find('size')# size = img.shape# w,h = size[1],size[0]w = int(size.find('width').text)h = int(size.find('height').text)for obj in root.iter('object'):# difficult = obj.find('difficult').textcls = obj.find('name').textif cls == 'mubiao':  # 修改处1cls = 0else:continuexmlbox = obj.find('bndbox')b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),float(xmlbox.find('ymax').text))bb = convert((w, h), b)out_file.write(str(cls) + " " + " ".join([str(a) for a in bb]) + '\n')wd = getcwd()list_file = os.listdir('xml')
for file in list_file:f = file.replace('.xml', '')convert_annotation(f)

labelmelabelImg项目相关推荐

  1. 在k8s中使用gradle构建java web项目镜像Dockerfile

    在k8s中使用gradle构建java web项目镜像Dockerfile FROM gradle:6-jdk8 AS build COPY --chown=gradle:gradle . /home ...

  2. Dockerfile springboot项目拿走即用,将yml配置文件从外部挂入容器

    Dockerfile 将springboot项目jar包打成镜像,并将yml配置文件外挂. # 以一个镜像为基础,在其上进行定制.就像我们之前运行了一个 nginx 镜像的容器,再进行修改一样,基础镜 ...

  3. SpringBoot项目使用nacos,kotlin使用nacos,java项目使用nacos,gradle项目使用nacos,maven项目使用nacos

    SpringBoot项目使用nacos kotlin demo见Gitte 一.引入依赖 提示:这里推荐使用2.2.3版本,springboot与nacos的依赖需要版本相同,否则会报错. maven ...

  4. Gradle 将项目publish到Nexus,Kotlin将项目发布到nexus,springboot项目发布到maven仓库

    示例见:Gitte 公仓设置 在项目中添加maven-publish的插件 plugins {kotlin("jvm") version "1.3.72"kot ...

  5. springboot项目使用junit4进行单元测试,maven项目使用junit4进行单元测试

    首先,maven项目中引入依赖 <dependency><groupId>junit</groupId><artifactId>junit</ar ...

  6. IDEA设置单个文件、单个包、单个项目的编码格式

    IDEA设置单个文件.单个包.单个项目的编码格式 File-> Settings-> File Enclodings 选择编码格式,确定即可. 注意:此处的编码格式设定以后,该包已经存在的 ...

  7. spring boot项目 中止运行 最常用的几种方法

    spring boot项目 中止运行 最常用的几种方法: 1. 调用接口,停止应用上下文 @RestController public class ShutdownController impleme ...

  8. 两步完成项目定时启动,java项目定时启动

    两步完成项目定时设置: 在需要定时启动或运行的方法上面加上注解@Scheduled //当天只跑一次 @Scheduled(cron = "0 40 21 * * ?") 在启动类 ...

  9. Myeclipse中项目没有代码错误提示,jsp页面无编译迹象?如何解决

    在使用Myeclipse开发项目时,发现jsp页面中嵌入的java代码没有编译的迹象,错误的get方法没有报错,没有报错信息我们如何知道我们开发的内容是正确的呢? 接下来就演示一下如何解决

最新文章

  1. 无监督学习距离监督学习还有多远?Hinton组新作解读
  2. python常见问题
  3. Interview:人工智能岗位面试—人工智能职位之计算机视觉算法工程师的简介、知识结构、发展方向之详细攻略
  4. mysql 架构优化_Mysql 架构及优化之-查询性能优化
  5. Servlet之javaweb应用(二)
  6. 5G的基站覆盖范围300米,今后边远地区的手机通话怎样保证?
  7. 【洛谷】P1052 过河(状压dp)
  8. perl中的sleep函数
  9. 条款27:尽量少做转型动作
  10. 2007年春节,祝朋友们:身体健康,万事如意! 度过一个愉快春节!
  11. mysql lvs+keepalived+mha_MHA+Lvs+Keepalived实现MySQL的高可用及读负载均衡_2(MySQL)
  12. 软件开发过程中需要的文档汇总
  13. 小郡肝火锅点餐系统——部分代码实现
  14. C++语言分号的使用
  15. 不动点求数列通项原理_【数列】浅谈“不动点”求数列通项的方法
  16. NI PXI-6221(16路模拟输入)校准小记
  17. Agent XPs disable
  18. 2021年团体程序设计天梯赛-总决赛 L3-2 还原文件
  19. 【pandas】 DataFrame缺失值的查找与填充
  20. Qt 绘制拖动刻度尺

热门文章

  1. 红帽Linux系统操作命令大全【linux查询命令篇】---转自微信公众号网络技术联盟站
  2. oracle数据库12c安装教程,Oracle12c安装教程|Oracle Database 12C安装及配置教程
  3. K-means算法原理、代码实现,优缺点及改进
  4. SNV的python实现
  5. 曲面积分的投影法_重积分3.二重积分的对称性
  6. 解决 Mac-osx Capitan 关闭Rootlees 安装 chromedriver
  7. 世界是数字的重点读书笔记(计算机科普知识)
  8. Kubernetes【升级】 CKS 2021【11】---Cluster Hardening - Upgrade Kubernetes
  9. 做跨境电商的绕不开亚马逊的原因你知道吗
  10. HTML5期末大作业:生活类购物商城网站设计——生活类购物商城模板(2页)学生商店网页作品