根据原作者源码及说明实践后总结
操作环境
Ubuntu 18.02 +cuda 11.1 +pytorch 1.9.0 作者源码下载:https://github.com/dog-qiuqiu/Yolo-FastestV2
配置环境
新建:
conda create -n yolov2 python=3.8
安装pytorch:
conda install pytorch torchvision torchaudio cudatoolkit=11.1 -c pytorch -c nvidia
下载源码:
git clone https://github.com/dog-qiuqiu/Yolo-FastestV2
安装依赖包:
pip install -r requirements.txt
测试图片:
python test.py --data data/coco.data --weights modelzoo/coco2017-0.241078ap-model.pth --img img/000139.jpg
测试成功!没有问题,就可以开始训练自己的数据集啦!
构建数据集:
此方法是将 voc 格式数据集转换为符合此算法的数据集格式 以下三个文件放在新建的data数据集里 使用maketxt.py划分测试集验证集
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()
划分好验证集测试集后,会在ImageSets文件中生成train.txt和val.txt 使用voc_label.py生成.txt标签文件 voc_label.py
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):
if os.path.getsize(path):
Size=os.path.getsize(path)
os.system('ls -lh %s' %(path))
return 1
else:
os.system('ls -lh %s' %(path))
return 2
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_id):
'''
将对应文件名的xml文件转化为label文件,xml文件包含了对应的bunding框以及图片长款大小等信息,
通过对其解析,然后进行归一化最终读到label文件中去,也就是说
一张图片文件对应一个xml文件,然后通过解析和归一化,能够将对应的信息保存到唯一一个label文件中去
labal文件中的格式:calss x y w h 同时,一张图片对应的类别有多个,所以对应的bunding的信息也有多个
'''
in_file = open('./data/Annotations/%s.xml' % (image_id), encoding='utf-8')
out_file = open('./data/JPEGimages/%s.txt' % (image_id), 'w', encoding='utf-8')
tree = ET.parse(in_file)
root = tree.getroot()
size = root.find('size')
if size != None:
w = int(size.find('width').text)
h = int(size.find('height').text)
for obj in root.iter('object'):
difficult= 0
if obj.find('difficult')!=None :
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))
bb = convert((w, h), b)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
wd = getcwd()
for image_set in sets:
'''
对所有的文件数据集进行遍历
做了两个工作:
1.将所有图片文件都遍历一遍,并且将其所有的全路径都写在对应的txt文件中去,方便定位
2.同时对所有的图片文件进行解析和转化,将其对应的bundingbox 以及类别的信息全部解析写到label 文件中去
最后再通过直接读取文件,就能找到对应的label 信息
'''
image_ids = open('./data/ImageSets/%s.txt' % (image_set)).read().strip().split()
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')
for image_id in image_ids:
list_file.write('./data/JPEGimages/%s%s\n' % (image_id, style))
pathxml='./data/Annotations/%s.xml' % (image_id)
xmlresult = ifnone(pathxml)
if xmlresult == 1 :
convert_annotation(image_id)
elif xmlresult == 2 :
path2 = './data/JPEGImages/%s.txt' % (image_id)
file = open(path2,'w')
print("end")
list_file.close()
计算锚点偏差
python3 genanchors.py --traintxt data/train.txt
计算以后会生成anchor6.txt,把第一行复制到data的coco.data里anchors里
coco.data和coco.names解析见其他文章
训练自己的数据集
python train.py --data data/coco.data
测试
python test.py --data data/coco.data --weights modelzoo/coco-140-epoch-0.872988ap-model.pth --img img/000005.jpg
测试多张图片用如下代码
import os
import cv2
import time
import argparse
import torch.nn as nn
import torch
import model.detector
import utils.utils
from thop import profile
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--data', type=str, default='',
help='Specify training profile *.data')
parser.add_argument('--weights', type=str, default='',
help='The path of the .pth model to be transformed')
parser.add_argument('--img', type=str, default='',
help='The path of test image')
opt = parser.parse_args()
cfg = utils.utils.load_datafile(opt.data)
assert os.path.exists(opt.weights), "./weights/best-model.pth"
assert os.path.exists(opt.img), "./data/voc/JPEGImages/000009.jpg"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.detector.Detector(cfg["classes"], cfg["anchor_num"], True).to(device)
model = nn.DataParallel(model)
model.to(device)
model.load_state_dict(torch.load(opt.weights, map_location=device))
model.eval()
for jpg in os.listdir(opt.img):
ori_img = os.path.join(opt.img, jpg)
print(ori_img)
ori_img = cv2.imread(ori_img)
res_img = cv2.resize(ori_img, (cfg["width"], cfg["height"]), interpolation=cv2.INTER_LINEAR)
img = res_img.reshape(1, cfg["height"], cfg["width"], 3)
img = torch.from_numpy(img.transpose(0, 3, 1, 2))
img = img.to(device).float() / 255.0
computertime = 0
start = time.perf_counter()
preds = model(img)
end = time.perf_counter()
computertime = (end - start) * 1000.
print("forward time:%fms" % computertime)
output = utils.utils.handel_preds(preds, cfg, device)
output_boxes = utils.utils.non_max_suppression(output, conf_thres=0.5, iou_thres=0.4)
LABEL_NAMES = []
with open(cfg["names"], 'r') as f:
for line in f.readlines():
LABEL_NAMES.append(line.strip())
h, w, _ = ori_img.shape
scale_h, scale_w = h / cfg["height"], w / cfg["width"]
for box in output_boxes[0]:
box = box.tolist()
obj_score = box[4]
category = LABEL_NAMES[int(box[5])]
x1, y1 = int(box[0] * scale_w), int(box[1] * scale_h)
x2, y2 = int(box[2] * scale_w), int(box[3] * scale_h)
cv2.rectangle(ori_img, (x1, y1), (x2, y2), (255, 255, 0), 2)
cv2.putText(ori_img, '%.2f' % obj_score, (x1, y1 - 5), 0, 0.7, (0, 255, 0), 2)
cv2.putText(ori_img, category, (x1, y1 - 25), 0, 0.7, (0, 255, 0), 2)
cv2.imwrite("datatest/testresult/{}.jpg".format(jpg.split(".")[0]), ori_img)
评估数据集
python3 evaluation.py --data data/coco.data --weights weights/best-model.pth
|