配置环境
- 查看电脑GPU版本
- 安装pytorch对应cuda 10.1
pip install torch==1.7.1+cu101 torchvision==0.8.2+cu101 torchaudio===0.7.2 -f https://download.pytorch.org/whl/torch_stable.html -i https://pypi.doubanio.com/simple --user
3. 配置训练数据
使用voc格式
数据集来自安全帽数据
4. 训练代码
链接
5. 训练数据配置先运行makeTxt.py,再运行voc_label.py(原作者voc_label.py处理安全帽数据爆GBK错误,这是修改后的源码)
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
sets = ['train', 'test','val']
classes = ["hat","person"]
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):
in_file = open('data/Annotations/%s.xml' % (image_id),encoding = 'UTF-8')
out_file = open('data/labels/%s.txt' % (image_id), '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'):
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()
print(wd)
for image_set in sets:
if not os.path.exists('data/labels/'):
os.makedirs('data/labels/')
image_ids = open('data/ImageSets/%s.txt' % (image_set),encoding = 'UTF-8').read().strip().split()
list_file = open('data/%s.txt' % (image_set), 'w')
for image_id in image_ids:
list_file.write('data/images/%s.jpg\n' % (image_id))
convert_annotation(image_id)
list_file.close()
- 删除原训练数据无关文件
- 运行训练命令(原作者命令有错,更改如下)
python train.py --data data/rbc.data --cfg cfg/yolov3-tiny.cfg --epochs 100
运行出错缺啥库就安装啥。
- 网吧CUDA内存报错。。。。发现cfg没改。
CUDA out of memory. Tried to allocate 1.15 GiB (GPU 0; 5.00 GiB total capaci
- 1 epoch
- 测试samples
python detect.py --data-cfg data/rbc.data --cfg cfg/yolov3-tiny.cfg --weights weights/best.pt
跑了一遍,效果能看见,结果不太好,网费有点贵,就不跑了。
工具包
需要将JPEGImages的图片复制到一份到images,为节省内存我删了。
网吧专用代码包