人脸数据集:WiderFace数据集
1.下载下面的四个压缩包,并放在同一个文件夹内
2. 在同一目录下解压4个压缩包,在当前目录下运行convert.py 转化为VOC格式数据集,完整代码如下:
(转化好的完整的voc格式的人脸数据集,点击打开,提取码:2cv4)
# -*- coding: utf-8 -*-
import shutil
import random
import os
import string
from skimage import io
headstr = """\
VOC2012
%06d.jpg
NULL
company
%d
%d
%d
0
"""
objstr = """\
"""
tailstr = '''\
'''
def writexml(idx, head, bbxes, tail):
filename = ("Annotations/%06d.xml" % (idx))
f = open(filename, "w")
f.write(head)
for bbx in bbxes:
f.write(objstr % ('face', bbx[0], bbx[1], bbx[0] + bbx[2], bbx[1] + bbx[3]))
f.write(tail)
f.close()
def clear_dir():
if shutil.os.path.exists(('Annotations')):
shutil.rmtree(('Annotations'))
if shutil.os.path.exists(('ImageSets')):
shutil.rmtree(('ImageSets'))
if shutil.os.path.exists(('JPEGImages')):
shutil.rmtree(('JPEGImages'))
shutil.os.mkdir(('Annotations'))
shutil.os.makedirs(('ImageSets/Main'))
shutil.os.mkdir(('JPEGImages'))
def excute_datasets(idx, datatype):
f = open(('ImageSets/Main/' + datatype + '.txt'), 'a')
f_bbx = open(('wider_face_split/wider_face_' + datatype + '_bbx_gt.txt'), 'r')
while True:
filename = f_bbx.readline().strip('\n')
if not filename:
break
im = io.imread(('WIDER_' + datatype + '/images/' + filename))
head = headstr % (idx, im.shape[1], im.shape[0], im.shape[2])
nums = f_bbx.readline().strip('\n')
bbxes = []
if nums=='0':
bbx_info= f_bbx.readline()
continue
for ind in range(int(nums)):
bbx_info = f_bbx.readline().strip(' \n').split(' ')
bbx = [int(bbx_info[i]) for i in range(len(bbx_info))]
# x1, y1, w, h, blur, expression, illumination, invalid, occlusion, pose
if bbx[7] == 0:
bbxes.append(bbx)
writexml(idx, head, bbxes, tailstr)
shutil.copyfile(('WIDER_' + datatype + '/images/' + filename), ('JPEGImages/%06d.jpg' % (idx)))
f.write('%06d\n' % (idx))
idx += 1
f.close()
f_bbx.close()
return idx
if __name__ == '__main__':
clear_dir()
idx = 1
idx = excute_datasets(idx, 'train')
idx = excute_datasets(idx, 'val')
print('Complete...')
3. 耐心等待运行完,数据量比较大,运行时间较长。结束后会生成3个文件夹,分别为:
4. 模仿VOC数据集的目录格式,将上面三个文件夹放在如下的层级目录下:
--VOCdevkit
--VOC2012
--Annotations //存放xml标签
--ImageSets
--Main //用txt文本存放图片的名称
--JPEGImages //存放所有JPG原图
--labels //存放yolo用的txt格式的标签
5. 将VOC的xml标签转化为YOLO要用的txt格式的标签,在VOCdevkit同级目录下运行voc_label.py:
"""
@Usage: generate custom voc-format-dataset labels, convert .xml to .txt for each image
@author: sun qian
@date: 2019/9/25
@note: dataset file structure must be modified as:
--VOCdevkit
--VOC2012
--Annotations
--ImageSets
--Main (include train.txt, test.txt, val.txt)
--JPEGImages
--labels
@ merge val and test: Run command: type 2012_test.txt 2012_val.txt > test.txt
"""
import xml.etree.ElementTree as ET
import os
from os import getcwd
# file list - train.txt, test.txt, val.txt
sets = [('2012', 'train'), ('2012', 'val')]
# class name
classes = ["face"]
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(year, image_id):
in_file = open('VOCdevkit/VOC%s/Annotations/%s.xml' % (year, image_id))
out_file = open('VOCdevkit/VOC%s/labels/%s.txt' % (year, 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')
if __name__ == '__main__':
wd = getcwd()
for year, image_set in sets:
if not os.path.exists('VOCdevkit/VOC%s/labels/' % (year)):
os.makedirs('VOCdevkit/VOC%s/labels/' % (year))
image_ids = open('VOCdevkit/VOC%s/ImageSets/Main/%s.txt' % (year, image_set)).read().strip().split()
list_file = open('%s_%s.txt' % (year, image_set), 'w')
for image_id in image_ids:
line = '%s/VOCdevkit/VOC%s/JPEGImages/%s.jpg\n' % (wd, year, image_id)
list_file.write(line.replace("\\", '/'))
convert_annotation(year, image_id)
list_file.close()
6. 结束后会在VOCdevkit -> VOC2012下生成labels和下面的2个txt文件(存放训练图片的绝对路径):
1.将2012_train.txt 和2012_val.txt复制到如下目录
../darknet-master/build/darknet/x64/data
2.在…/darknet-master/build/darknet/x64/data下新建文件face.data,打开face.data并写入:
classes= 1
train = data/2012_train.txt
valid = data/2012_val.txt
names = data/face.names
backup = data/weights-face
3.在…/darknet-master/build/darknet/x64/data下新建文件face.names,打开face.names并写入:
face
4.在…/darknet-master/build/darknet/x64/data下新建一个文件夹weights-face,用于存放训练的权重。
5.在…/darknet-master/build/darknet/x64中找到yolov3.cfg,复制一份到…/x64/data目录下,重命名为yolov3-face.cfg(已修改好,可直接下载使用)。
6. yolov3-face.cfg主要改动的地方有三点:
filters=18
classes=1
#在../darknet-master/build/darknet/x64 目录下运行如下CMD代码,最后会生成anchors.txt
darknet.exe detector calc_anchors data/face.data -num_of_clusters 9 -width 416 -height 416
7.下载预训练模型darknet53.conv.74 放在:
..darknet-master/build/darknet/x64/data
8.命令行下进入…/darknet-master/build/darknet/x64,然后执行下面的命令开始训练:
darknet.exe detector train ./data/face.data ./data/yolov3-face.cfg ./data/darknet53.conv.74
1. 由于WIDER Face数据集非常复杂,在RTX 2080Ti上经过20个小时的训练迭代17500次,loss一直稳定在2.0左右,可以结束训练来测试一下人脸检测的效果了。
2. cd进入…darknet-master\build\darknet\x64,在cmd中执行下面的命令,开始测试单一图像:
darknet.exe detector test data/face.data data/yolov3-face.cfg data/weights-face/yolov3-face_last.weights -thresh 0.4
3. 在百度上随便找了几张含有人脸的图像,试试yolov3人脸检测器的效果。