1.img_label对比脚本
# -*-coding:utf-8-*-
# @编译环境:windows 10 + python3.8
# @IDE:Pycharm2021.1.3
import glob
list1 = glob.glob('D:/Desktop/test/images/*g')
list2 = glob.glob('D:/Desktop/test/xml/*l')
s1 = [None] * len(list1)
s2 = [None] * len(list2)
for i in range(len(list1)):
s1[i] = list1[i].replace('D:/Desktop/test/images\\', '')
s1[i] = s1[i].replace('.jpg', '')
for i in range(len(list2)):
s2[i] = list2[i].replace("D:/Desktop/test/xml\\", '')
s2[i] = s2[i].replace('.xml', '')
print(set(s2) - set(s1))
2.判断文本文件是否为空_脚本
# -*-coding:utf-8-*-
# @编译环境:windows 10 + python3.8
# @IDE:Pycharm2021.1.3
import os, glob
list = glob.glob(r'D:\Python\pycharm project\yolov5\PCB\train\labels\*t')
print(len(list))
for i, l in enumerate(list):
with open(l, 'r') as f:
f.seek(0)
if f.read() == '':
print(l)
3.多文件夹图片标签同时重命名
# -*-coding:utf-8-*-
# @编译环境:windows 10 + python3.8
# @IDE:Pycharm2021.1.3
import os, sys # 导入模块
def rename_subfolders(s, path1, path2, c): # 定义函数名称
num = 1
old_names = os.listdir(path1) # 取路径下的文件名,生成列表
print(f'{c:}= ' + str(len(old_names)))
for old_name in old_names: # 遍历列表下的文件名
os.rename(os.path.join(path1, old_name), os.path.join(path1, f'{c:}_' + str(num)) + ".xml")
old_name = old_name.replace(f'D:\Desktop\{s:}labels', '')
old_name = old_name.replace('.xml', '.jpg')
os.rename(os.path.join(path2, old_name), os.path.join(path2, f'{c:}_' + str(num)) + ".jpg")
num = num + 1
if __name__ == '__main__':
fs = ['文件夹1', '文件夹2', '文件夹3', '文件夹4', '文件夹5', '文件夹6', '文件夹7', '文件夹8', '文件夹9', '文件夹10']
c = 0
for s in fs:
path1 = rf'D:\Desktop\{s:}labels'
path2 = rf'D:\Desktop\{s:}'
rename_subfolders(s, path1, path2, str(c))
c += 1
xml to yolo
# -*-coding:utf-8-*-
# @编译环境:windows 10 + python3.8
# @IDE:Pycharm2021.1.3
import os
import pickle
import xml.etree.ElementTree as ET
from os import listdir, getcwd
from os.path import join
import glob
classes = ['类名1', '类名2', '类名3', '类名4', '类名5', '类名6']
def convert(size, box):
dw = 1. / size[0]
dh = 1. / size[1]
x = (box[0] + box[1]) / 2.0
y = (box[2] + box[3]) / 2.0
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 convert_annotation(image_name):
in_file = open('./ANNOTATIONS/' + image_name[:-3] + 'xml')
out_file = open('./LABELS/' + image_name[:-3] + 'txt', 'w')
tree = ET.parse(in_file)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
for obj in root.iter('object'):
cls = obj.find('name').text
if cls not in classes:
print(cls)
continue
cls_id = classes.index(cls)
xmlbox = 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_id) + ' ' + ' '.join([str(a) for a in bb]) + '\n')
wd = getcwd()
if __name__ == '__main__':
for image_path in glob.glob('./IMAGES/*.jpg'):
image_name = image_path.split('\\')[-1]
convert_annotation(image_name)