1.环境
最好有conda环境,没有也没关系
pip install labelImg
目录结构
yolov5
|---labelImg
|---yolo_data
|---images
|---ann
|---labels
|---predefined_classes.txt
|---voc2yolo.py
文件中predefined_classes.txt写预定义类别,随便自己起名
hoe
chess
table
lego2
stove
vase
voc2yolo.py内容
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
def convert(size, box):
x_center = (box[0] + box[1]) / 2.0
y_center = (box[2] + box[3]) / 2.0
x = x_center / size[0]
y = y_center / size[1]
w = (box[1] - box[0]) / size[0]
h = (box[3] - box[2]) / size[1]
return (x, y, w, h)
def convert_annotation(xml_files_path, save_txt_files_path, classes):
xml_files = os.listdir(xml_files_path)
print(xml_files)
for xml_name in xml_files:
print(xml_name)
xml_file = os.path.join(xml_files_path, xml_name)
out_txt_path = os.path.join(save_txt_files_path, xml_name.split('.')[0] + '.txt')
out_txt_f = open(out_txt_path, 'w')
tree = ET.parse(xml_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'):
difficult = obj.find('difficult').text
cls = obj.find('name').text
if cls not in classes or int(difficult) == 1:
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))
# b=(xmin, xmax, ymin, ymax)
print(w, h, b)
bb = convert((w, h), b)
out_txt_f.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
if __name__ == "__main__":
# 需要转换的类别,需要一一对应
classes1 = ['horncenter', 'hornleft','leaves','orc']
# 2、voc格式的xml标签文件路径
xml_files1 = r'ann'
# 3、转化为yolo格式的txt标签文件存储路径
save_txt_files1 = r'label'
convert_annotation(xml_files1, save_txt_files1, classes1)
2.标注
运行
labelImg images predefined_classes.txt
选项栏-查看-自动保存模式开启
按w,拖出框,选择类别(类别正确直接回车),按d下一张
3.修改voc2yolo.py内容classes1 = ['horncenter', 'hornleft','leaves','orc']为对应类别
4.改变文件夹结构
--image
|----train
|----image1.jpg(随便)
|----image2.jpg(随便)
...
|----val(和train一样就行)
|----image1.jpg(随便)
|----image2.jpg(随便)
...
--label
|----train
|----image1.txt(随便)
|----image2.txt(随便)
...
|----val(和train一样就行)
|----image1.txt(随便)
|----image2.txt(随便)
...
5.修改yolov5 -> data -> nerf.yaml的
path: labelImg/yolo_data/ # 这里是放你标记好文件的目录
train: # train images (relative to 'path') 16551 images
- images/train
val: # val images (relative to 'path') 4952 images
- images/val
# 这也得该
names:
0: shoe
1: chess
2: table
3: lego2
4: stove
5: vase
6.修改yolov5 -> models -> yolov5s.yaml(可以是yolov5x等别的,选对应使用的原始模型就行)的
nc: 6 # number of classes
7.运行
python train.py --weight yolov5s.pt --cfg models/yolov5s.yaml --data data/nerf.yaml
8.结果模型在runs -> train 下exp最新
9.测试最新的模型,你需要把exp最新下weights里的best拷贝到yolov5目录下
python detect.py --weight best.pt
由以下文章改写
————————————————
版权声明:本文为CSDN博主「炮哥带你学」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/didiaopao/article/details/119954291