1,images,annotations创建
IMAGES:放图片材料的
ANNTATIONS:放labelImg标记的xml文件
2,labels,txt怎么来的
labels :可以手动创建,里面还配置了train,val,test文件夹。可手动(以下代码中没有写)
txt:由一下代码自动生成,前提是images,annotations需要自己去创建
3,xml2txt.py
images,annotations有了之后直接运行一下代码
import xml.etree.ElementTree as ET
import os, cv2
import numpy as np
from os import listdir
from os.path import join
classes = []
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 convert_annotation(xmlpath, xmlname):
with open(xmlpath, "r", encoding='utf-8') as in_file:
txtname = xmlname[:-4] + '.txt'
txtfile = os.path.join(txtpath, txtname)
tree = ET.parse(in_file)
root = tree.getroot()
filename = root.find('filename')
img = cv2.imdecode(np.fromfile('{}/{}.{}'.format(imgpath, xmlname[:-4], postfix), np.uint8), cv2.IMREAD_COLOR)
h, w = img.shape[:2]
res = []
for obj in root.iter('object'):
cls = obj.find('name').text
if cls not in classes:
classes.append(cls)
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)
res.append(str(cls_id) + " " + " ".join([str(a) for a in bb]))
if len(res) != 0:
with open(txtfile, 'w+') as f:
f.write('\n'.join(res))
if __name__ == "__main__":
postfix = 'jpg'
imgpath = 'VOCdevkit/images'
xmlpath = 'VOCdevkit/annnotations'
txtpath = 'VOCdevkit/txt'
if not os.path.exists(txtpath):
os.makedirs(txtpath, exist_ok=True)
list = os.listdir(xmlpath)
error_file_list = []
for i in range(0, len(list)):
try:
path = os.path.join(xmlpath, list[i])
if ('.xml' in path) or ('.XML' in path):
convert_annotation(path, list[i])
print(f'file {list[i]} convert success.')
else:
print(f'file {list[i]} is not xml format.')
except Exception as e:
print(f'file {list[i]} convert error.')
print(f'error message:\n{e}')
error_file_list.append(list[i])
print(f'this file convert failure\n{error_file_list}')
print(f'Dataset Classes:{classes}')
4,split_data.py
此文件是以上代码执行完毕执行,前提需要有labels文件夹
import os, shutil, random
random.seed(0)
import numpy as np
source_path=r'D:/BRWork/ultralytics-main/datesets/VOCdevkit/'
val_size = 0.1
test_size = 0.2
postfix = 'jpg'
imgpath = source_path+'images'
txtpath = source_path+'txt'
os.makedirs('VOCdevkit/images/train', exist_ok=True)
os.makedirs('VOCdevkit/images/val', exist_ok=True)
os.makedirs('VOCdevkit/images/test', exist_ok=True)
os.makedirs('labels/train', exist_ok=True)
os.makedirs('labels/val', exist_ok=True)
os.makedirs('labels/test', exist_ok=True)
listdir = np.array([i for i in os.listdir(txtpath) if 'txt' in i])
print(listdir)
random.shuffle(listdir)
train, val, test = listdir[:int(len(listdir) * (1 - val_size - test_size))], listdir[int(len(listdir) * (1 - val_size - test_size)):int(len(listdir) * (1 - test_size))], listdir[int(len(listdir) * (1 - test_size)):]
print(f'train set size:{len(train)} val set size:{len(val)} test set size:{len(test)}')
for i in train:
shutil.copy('{}/{}.{}'.format(imgpath, i[:-4], postfix), source_path+'images/train/{}.{}'.format(i[:-4], postfix))
shutil.copy('{}/{}'.format(txtpath, i), source_path+'labels/train/{}'.format(i))
for i in val:
shutil.copy('{}/{}.{}'.format(imgpath, i[:-4], postfix), source_path+'images/val/{}.{}'.format(i[:-4], postfix))
shutil.copy('{}/{}'.format(txtpath, i), source_path+'labels/val/{}'.format(i))
for i in test:
shutil.copy('{}/{}.{}'.format(imgpath, i[:-4], postfix), source_path+'images/test/{}.{}'.format(i[:-4], postfix))
shutil.copy('{}/{}'.format(txtpath, i), source_path+'labels/test/{}'.format(i))
5,路径问题
以上文件路径自定义修改
6,文件运行不起来的问题data.yaml
全部写成绝对路径:
train: D:\BRWork\ultralytics-main\datesets\VOCdevkit\images\train
val: D:\BRWork\ultralytics-main\datesets\VOCdevkit\images\test
test: D:\BRWork\ultralytics-main\datesets\VOCdevkit\images\test
nc: 2
names: ['crack1', 'crack2']
7.运行文件,训练
也需要写成绝对路径。我的是cpu训练的,gpu训练自行调整
from ultralytics import YOLO
# model = YOLO("../yolov8n.pt")
#
# results = model.train(data=r"D:\BRWork\ultralytics-main\data.yaml", imgsz=320, epochs=120, batch=16, device='cpu', workers=0)
8,运行效果