当前位置:网站首页>The XML format of labelimg annotation is converted to yolov5
The XML format of labelimg annotation is converted to yolov5
2022-07-27 02:35:00 【AI Hao】
import os
import shutil
import numpy as np
import json
from glob import glob
import cv2
from sklearn.model_selection import train_test_split
from os import getcwd
import xml.etree.ElementTree as ET
def convert(size, box):
dw = 1. / (size[0])
dh = 1. / (size[1])
x = (box[0] + box[1]) / 2.0 - 1
y = (box[2] + box[3]) / 2.0 - 1
w = box[1] - box[0]
h = box[3] - box[2]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return (x, y, w, h)
def change_2_yolo5(files, txt_Name):
classes = ["No"]
imag_name=[]
for json_file_ in files:
xml_filename = labelme_path + json_file_ + ".xml"
out_file = open('%s/%s.txt' % (labelme_path, json_file_), 'w')
# image_path = labelme_path + json_file['imagePath']
height, width, channels = cv2.imread(labelme_path + json_file_ + ".jpg").shape
in_file=open(xml_filename,encoding='utf-8')
tree = ET.parse(in_file)
root = tree.getroot()
imag_name.append(root.find('filename').text)
for obj in root.iter('object'):
xmlbox = obj.find('bndbox')
cls = obj.find('name').text
if cls not in classes :
continue
cls_id = classes.index(cls)
xmin = int(float(xmlbox.find('xmin').text)) if int(float(xmlbox.find('xmin').text))> 0 else 0
xmax =int(float(xmlbox.find('xmax').text)) if int(float(xmlbox.find('xmax').text)) > 0 else 0
ymin = int(float(xmlbox.find('ymin').text)) if int(float(xmlbox.find('ymin').text)) > 0 else 0
ymax =int(float(xmlbox.find('ymax').text)) if int(float(xmlbox.find('ymax').text)) > 0 else 0
b = (float(xmin), float(xmax), float(ymin), float(ymax))
bb = convert((width, height), b)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
return imag_name
def image_txt_copy(files,scr_path,dst_img_path,dst_txt_path):
""" :param files: Picture name list :param scr_path: Path to picture :param dst_img_path: The path where the picture is copied :param dst_txt_path: The picture corresponds to txt Path copied to :return: """
for file in files:
img_path=scr_path+file
shutil.copy(img_path, dst_img_path+file)
scr_txt_path=scr_path+file.split('.')[0]+'.txt'
shutil.copy(scr_txt_path, dst_txt_path + file.split('.')[0]+'.txt')
if __name__ == '__main__':
classes = ["No"]
# 1. Tag path
labelme_path = "Annotations/"
# 3. Get the pending file
files = glob(labelme_path + "*.xml")
files = [i.replace("\\", "/").split("/")[-1].split(".xml")[0] for i in files]
trainval_files, test_files = train_test_split(files, test_size=0.1, random_state=55)
# split
train_files, val_files = train_test_split(trainval_files, test_size=0.1, random_state=55)
train_name_list=change_2_yolo5(train_files, "train")
print(train_name_list)
val_name_list=change_2_yolo5(val_files, "val")
test_name_list=change_2_yolo5(test_files, "test")
# Create dataset folder .
file_List = ["train", "val", "test"]
for file in file_List:
if not os.path.exists('./VOC/images/%s' % file):
os.makedirs('./VOC/images/%s' % file)
if not os.path.exists('./VOC/labels/%s' % file):
os.makedirs('./VOC/labels/%s' % file)
image_txt_copy(train_name_list,labelme_path,'./VOC/images/train/','./VOC/labels/train/')
image_txt_copy(val_name_list, labelme_path, './VOC/images/val/', './VOC/labels/val/')
image_txt_copy(test_name_list, labelme_path, './VOC/images/test/', './VOC/labels/test/')
边栏推荐
- Is it useful to lie down with your eyes closed when you can't sleep?
- C language - assignment operator, compound assignment operator, self increasing and self decreasing operator, comma operator, conditional operator, goto statement, comment
- 30岁被裁,我想明白的几件事....
- 【封神演绎、十五分钟让你彻底学会栈的使用!!!】
- 最新多线程&高并发学习资料,面试心里有底气
- 证券炒股开户需要现场开户吗网上开户安全吗
- How does the whole network display IP ownership?
- Find a specific number in an ordered array
- C language - value range of data type and basic data type
- HCIP 双向重发布以及路由策略
猜你喜欢

Risc-v tool chain compilation notes

The pointer is really profound!!!
![[dimension reduction blow, take you to learn CPU in depth (Part 1)]](/img/59/0c2b8e1a832ef14e2e0b8e8cdcce9c.png)
[dimension reduction blow, take you to learn CPU in depth (Part 1)]

JMeter下载安装

祝大家七夕快乐,邀你源码共读

Little sister's notes: how do I learn simple source code to expand my horizons

OSPF basic experimental configuration

【在Visual Studio 2019中使用SQLite3库实现学生信息管理系统】

Sort the three integers from large to small (introduce various methods in detail)

膜拜,阿里内部都在强推的321页互联网创业核心技术pdf,真的跪了
随机推荐
Hcip day 3 Wan topology experiment
Today, let's talk about escape characters [cute new version]
HCIP-第二天
oSPF基础实验配置
Record the nth SQL exception
Multipoint bidirectional republication and routing strategy topology experiment
C language student information management system can access text files based on arrays
【封神演绎、十五分钟让你彻底学会栈的使用!!!】
Prometheus 运维工具 Promtool (三) Debug 功能
C language -- nesting of relational and logical operators, if statements, switch statements, and branch structures
go语言慢速入门——go运算符
TCP三次握手、四次断开
What is the principle of synchronized lock escalation in multithreading?
excel整行删除,图片一起删除
RIP路由信息协议-拓扑实验
Hcip OSPF knowledge summary
Hcip OSPF comprehensive experiment
Fist guessing applet based on Object-C novice on the road
Handsomeforum Learning Forum
打开编程的大门