https://github.com/Microsoft/VoTT
数据集制作新建工程:
项目设置:
导出设置:格式为Pascal VOC,数据集:Only tagged
图片标记:R
导出数据集:Ctrl+E
导出结果:
cd Yolo-FastestV2 && mkdir -p ./data/labels/ echo """
# -*- coding: UTF-8 -*-
import os
import random
trainval_percent = 0.1
train_percent = 1
xmlfilepath = './data/Annotations'
total_xml = os.listdir(xmlfilepath)
num = len(total_xml)
list = range(num)
tv = int(num * trainval_percent)
trainval = random.sample(list, tv)
txt_train='./data/ImageSets/train.txt'
if os.path.exists(txt_train):
os.remove(txt_train)
else:
open(txt_train,'w')
txt_val='./data/ImageSets/val.txt'
if os.path.exists(txt_val):
os.remove(txt_val)
else:
open(txt_val,'w')
ftrain = open(txt_train, 'w')
fval = open(txt_val, 'w')
for i in list:
name = total_xml[i][:-4] + 'n'
ftrain.write(name)
if i in trainval:
fval.write(name)
ftrain.close()
fval.close()
"""> maketxt.py
python3 maketxt.py 会在data/ImageSets文件夹中生成train.txt和val.txt
生成.txt标签文件根据需要修改内容
echo """
# -*- coding: utf-8 -*-
# xml解析包
import xml.etree.ElementTree as ET
import os
from os import getcwd
import shutil
sets = ['train', 'val']
classes = ['apple','cup','house'] #根据需要修改
style = '.jpg' #根据需要修改
#判断文件是否为空
def ifnone(path) :
if os.path.exists(path):
#print("文件存在")
if os.path.getsize(path):
#print("文件存在且不为空")
#print(os.path.getsize(FILE))
Size=os.path.getsize(path)
os.system('ls -lh %s' %(path))
return 1
else:
#print("文件存在但为空...")
os.system('ls -lh %s' %(path))
return 2
# 进行归一化操作
def convert(size, box): # size:(原图w,原图h) , box:(xmin,xmax,ymin,ymax)
dw = 1. / size[0] # 1/w
dh = 1. / size[1] # 1/h
x = (box[0] + box[1]) / 2.0 # 物体在图中的中心点x坐标
y = (box[2] + box[3]) / 2.0 # 物体在图中的中心点y坐标
w = box[1] - box[0] # 物体实际像素宽度
h = box[3] - box[2] # 物体实际像素高度
x = x * dw # 物体中心点x的坐标比(相当于 x/原图w)
w = w * dw # 物体宽度的宽度比(相当于 w/原图w)
y = y * dh # 物体中心点y的坐标比(相当于 y/原图h)
h = h * dh # 物体宽度的宽度比(相当于 h/原图h)
return (x, y, w, h) # 返回 相对于原图的物体中心点的x坐标比,y坐标比,宽度比,高度比,取值范围[0-1]
# year ='2012', 对应图片的id(文件名)
def convert_annotation(image_id):
'''
将对应文件名的xml文件转化为label文件,xml文件包含了对应的bunding框以及图片长款大小等信息,通过对其解析,然后进行归一化最终读到label文件中去,也就是说一张图片文件对应一个xml文件,然后通过解析和归一化,能够将对应的信息保存到唯一一个label文件中去label文件中的格式:calss x y w h同时,一张图片对应的类别有多个,所以对应的bunding的信息也有多个
'''
# 对应的通过year 找到相应的文件夹,并且打开相应image_id的xml文件,其对应bund文件
in_file = open('./data/Annotations/%s.xml' % (image_id), encoding='utf-8')
# 准备在对应的image_id 中写入对应的label,分别为
#
out_file = open('./data/labels/%s.txt' % (image_id), 'w', encoding='utf-8')
# 解析xml文件
tree = ET.parse(in_file)
# 获得对应的键值对
root = tree.getroot()
# 获得图片的尺寸大小
size = root.find('size')
# 如果xml内的标记为空,增加判断条件
if size != None:
# 获得宽
w = int(size.find('width').text)
# 获得高
h = int(size.find('height').text)
# 遍历目标obj
for obj in root.iter('object'):
# 获得difficult ??
difficult= 0
if obj.find('difficult')!=None :
difficult = obj.find('difficult').text
# 获得类别 =string 类型
cls = obj.find('name').text
#print("display",image_id,cls,difficult)
# 如果类别不是对应在我们预定好的class文件中,或difficult==1则跳过
if cls not in classes or int(difficult) == 1:
continue
# 通过类别名称找到id
cls_id = classes.index(cls)
# 找到bndbox 对象
xmlbox = obj.find('bndbox')
# 获取对应的bndbox的数组 = ['xmin','xmax','ymin','ymax']
b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
float(xmlbox.find('ymax').text))
#print(image_id, cls, b)
# 带入进行归一化操作
# w = 宽, h = 高, b= bndbox的数组 = ['xmin','xmax','ymin','ymax']
bb = convert((w, h), b)
# bb 对应的是归一化后的(x,y,w,h)
# 生成 calss x y w h 在label文件中
out_file.write(str(cls_id) + ' ' + ' '.join([str(a) for a in bb]) + 'n')
# 返回当前工作目录
wd = getcwd()
#print(wd)
# 先找labels文件夹如果不存在则创建
#labels = './data/labels'
#if os.path.exists(labels):
# shutil.rmtree(labels) # delete output folder
#os.makedirs(labels) # make new output folder
for image_set in sets:
'''
对所有的文件数据集进行遍历
做了两个工作:
1.将所有图片文件都遍历一遍,并且将其所有的全路径都写在对应的txt文件中去,方便定位
2.同时对所有的图片文件进行解析和转化,将其对应的bundingbox 以及类别的信息全部解析写到label 文件中去
最后再通过直接读取文件,就能找到对应的label 信息
'''
# 读取在ImageSets/Main 中的train、test..等文件的内容
# 包含对应的文件名称
image_ids = open('./data/ImageSets/%s.txt' % (image_set)).read().strip().split()
# 打开对应的2012_train.txt 文件对其进行写入准备
txt_name = './data/%s.txt' % (image_set)
if os.path.exists(txt_name):
os.remove(txt_name)
else:
open(txt_name, 'w')
list_file = open(txt_name, 'w')
# 将对应的文件_id以及全路径写进去并换行
for image_id in image_ids:
list_file.write('./data/JPEGImages/%s%sn' % (image_id, style))
# 调用 year = 年份 image_id = 对应的文件名_id
#print(image_id)
pathxml='./data/Annotations/%s.xml' % (image_id)
xmlresult = ifnone(pathxml)#判断xml是否有空文件
if xmlresult == 1 :
convert_annotation(image_id)
elif xmlresult == 2 :
path2 = './data/labels/%s.txt' % (image_id)
file = open(path2,'w')
# 关闭文件
print('end')
list_file.close()
"""> voc_label.py
python3 voc_label.py 会生成.txt标签文件
计算锚点偏差python3 genanchors.py --traintxt ./data/train.txt
计算以后会生成 anchor6.txt,把第一行复制到data/coco.data的anchors里,修改[data-configure]下面的内容
制作分类文件data/coco.names,内容为标签,一行一个
最终Yolo-FastestV2目录结构如下
Yolo-FastestV2
├── data
│ ├── Annotations
│ │ ├── 1.xml
│ │ ├── 2.xml
│ │ ├── 3.xml
│ │ ├── 4.xml
│ │ └── ***.xml
│ ├── coco.data
│ ├── coco.names
│ ├── ImageSets
│ │ ├── Main
│ │ │ ├── tag_train.txt
│ │ │ └── tag_val.txt
│ │ ├── train.txt
│ │ └── val.txt
│ ├── JPEGImages
│ │ ├── 1.jpg
│ │ ├── 2.jpg
│ │ ├── 3.jpg
│ │ ├── 4.jpg
│ │ └── ***.jpg
│ ├── labels
│ │ ├── 1.txt
│ │ ├── 2.txt
│ │ ├── 3.txt
│ │ ├── 4.txt
│ │ └── ***.txt
│ ├── train.txt
│ └── val.txt
├── evaluation.py
├── genanchors.py
├── img
│ ├── 000004.jpg
│ ├── 000004_result.png
│ ├── 000139.jpg
│ ├── 000139_result.png
│ ├── 000148.jpg
│ ├── 000148_result.png
│ ├── 000181.jpg
│ ├── 000181_result.png
│ ├── 000230.jpg
│ ├── 000230_result.png
│ └── demo.png
├── maketxt.py
├── model
│ ├── backbone
│ │ ├── backbone.pth
│ │ ├── __pycache__
│ │ │ └── shufflenetv2.cpython-39.pyc
│ │ └── shufflenetv2.py
│ ├── detector.py
│ ├── fpn.py
│ └── __pycache__
│ ├── detector.cpython-39.pyc
│ └── fpn.cpython-39.pyc
├── modelzoo
│ └── coco2017-0.241078ap-model.pth
├── pytorch2onnx.py
├── README.md
├── requirements.txt
├── sample
│ └── ncnn
│ ├── build.sh
│ ├── demo.cpp
│ ├── model
│ │ ├── yolo-fastestv2-opt.bin
│ │ └── yolo-fastestv2-opt.param
│ ├── output.png
│ ├── src
│ │ ├── include
│ │ │ └── yolo-fastestv2.h
│ │ └── yolo-fastestv2.cpp
│ └── test.jpg
├── test.py
├── test_result.png
├── train.py
├── utils
│ ├── datasets.py
│ ├── loss.py
│ ├── __pycache__
│ │ └── utils.cpython-39.pyc
│ └── utils.py
├──voc_label.py
└── weights
└── README.md
训练数据集
utils/datasets.py 的 87 行开始
with open(self.path, 'r') as f:
for line in f.readlines():
data_path = line.strip()
if os.path.exists(data_path):
img_type = data_path.split(".")[-1]
if img_type not in self.img_formats:
raise Exception("img type error:%s" % img_type)
else:
self.data_list.append(data_path)
elif os.path.exists(data_path.replace("jpg", "png")):
self.data_list.append(data_path.replace("jpg", "png"))
else:
raise Exception("%s is not exist" % data_path)
103 行改为
label_path = "./data/labels/" + img_path.split("/")[-1].split(".")[0] + ".txt"
137 行修改为
data = TensorDataset("./data/train.txt")
开始训练
python3 train.py --data data/coco.data测试模型
python3 test.py --data data/coco.data --weights weights/coco-上一步训练结果.pth --img 识别图片.jpg评估训练结果
python3 evaluation.py --data data/coco.data --weights weights/coco-最终训练.pth转换模型文件
pth>onnx
cd Yolo-FastestV2 python3 pytorch2onnx.py --data data/coco.data --weights modelzoo/训练结果.pth --output yolo-fastestv2.onnx
onnx瘦身
python3 -m onnxsim yolo-fastestv2.onnx yolo-fastestv2-opt.onnx
onnx>ncnn
cd ncnn/build/tools/onnx ./onnx2ncnn yolo-fastestv2-opt.onnx yolo-fastestv2.param yolo-fastestv2.bin cp yolo-fastestv2* ../ cd ../ ./ncnnoptimize yolo-fastestv2.param yolo-fastestv2.bin yolo-fastestv2-opt.param yolo-fastestv2-opt.bin 1 cp yolo-fastestv2-opt* ~/Yolo-FastestV2/sample/ncnn/model



