yolov4 訓練自己的數據集--人頭識別

0、實驗環境

ubuntu 16.04
opencv 3.4.10
cuda 10.1

1、yolov4安裝

1.1、下載編譯darknet

darknet下載地址

git clone https://github.com/AlexeyAB/darknet
cd darknet

darknet 默認編譯是不帶cuda與opencv,而且不會編譯so文件。如果想編譯帶有cuda與opencv,並編譯so文件的需要修改Makefile
在這裏插入圖片描述
進行編譯

make -j8 

2、準備數據集

數據集我是從此處下載的(謝謝分享)。爲了方便下載我也留一下下載地址 Images -Annotations - 這些標籤是xml的不是yolov4格式需要變成yolov4格式。於是從網上找到了一個腳本文件(謝謝網友的分享)。這個腳本文件要求數據的目錄格式是VOC可是的。如下圖
在這裏插入圖片描述
把腳本放在darknet目錄下與VOCdevkit同級目錄。腳本如下

import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
import random

classes=["head"]   #此處要改成自己的標籤類別名稱


def clear_hidden_files(path):
    dir_list = os.listdir(path)
    for i in dir_list:
        abspath = os.path.join(os.path.abspath(path), i)
        if os.path.isfile(abspath):
            if i.startswith("._"):
                os.remove(abspath)
        else:
            clear_hidden_files(abspath)

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('VOCdevkit/VOC2007/Annotations/%s.xml' %image_id)
    out_file = open('VOCdevkit/VOC2007/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))
        #print("image_id = %s\n" %image_id)
        bb = convert((w,h), b)
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
    in_file.close()
    out_file.close()

wd = os.getcwd()
wd = os.getcwd()
work_sapce_dir = os.path.join(wd, "VOCdevkit/")
if not os.path.isdir(work_sapce_dir):
    os.mkdir(work_sapce_dir)
work_sapce_dir = os.path.join(work_sapce_dir, "VOC2007/")
if not os.path.isdir(work_sapce_dir):
    os.mkdir(work_sapce_dir)
annotation_dir = os.path.join(work_sapce_dir, "Annotations/")
if not os.path.isdir(annotation_dir):
        os.mkdir(annotation_dir)
clear_hidden_files(annotation_dir)
image_dir = os.path.join(work_sapce_dir, "JPEGImages/")
if not os.path.isdir(image_dir):
        os.mkdir(image_dir)
clear_hidden_files(image_dir)
VOC_file_dir = os.path.join(work_sapce_dir, "ImageSets/")
if not os.path.isdir(VOC_file_dir):
        os.mkdir(VOC_file_dir)
VOC_file_dir = os.path.join(VOC_file_dir, "Main/")
if not os.path.isdir(VOC_file_dir):
        os.mkdir(VOC_file_dir)

train_file = open(os.path.join(wd, "2007_train.txt"), 'w')
test_file = open(os.path.join(wd, "2007_test.txt"), 'w')
train_file.close()
test_file.close()
VOC_train_file = open(os.path.join(work_sapce_dir, "ImageSets/Main/train.txt"), 'w')
VOC_test_file = open(os.path.join(work_sapce_dir, "ImageSets/Main/test.txt"), 'w')
VOC_train_file.close()
VOC_test_file.close()
if not os.path.exists('VOCdevkit/VOC2007/labels'):
    os.makedirs('VOCdevkit/VOC2007/labels')
train_file = open(os.path.join(wd, "2007_train.txt"), 'a')
test_file = open(os.path.join(wd, "2007_test.txt"), 'a')
VOC_train_file = open(os.path.join(work_sapce_dir, "ImageSets/Main/train.txt"), 'a')
VOC_test_file = open(os.path.join(work_sapce_dir, "ImageSets/Main/test.txt"), 'a')
list = os.listdir(image_dir) # list image files
probo = random.randint(1, 100)
print("Probobility: %d" % probo)
for i in range(0,len(list)):
    path = os.path.join(image_dir,list[i])
    if os.path.isfile(path):
        image_path = image_dir + list[i]
        voc_path = list[i]
        (nameWithoutExtention, extention) = os.path.splitext(os.path.basename(image_path))
        (voc_nameWithoutExtention, voc_extention) = os.path.splitext(os.path.basename(voc_path))
        annotation_name = nameWithoutExtention + '.xml'
        annotation_path = os.path.join(annotation_dir, annotation_name)
    probo = random.randint(1, 100)
    print("Probobility: %d" % probo)
    if(probo < 80):
        if os.path.exists(annotation_path):
            train_file.write(image_path + '\n')
            VOC_train_file.write(voc_nameWithoutExtention + '\n')
            convert_annotation(nameWithoutExtention)
    else:
        if os.path.exists(annotation_path):
            test_file.write(image_path + '\n')
            VOC_test_file.write(voc_nameWithoutExtention + '\n')
            convert_annotation(nameWithoutExtention)
train_file.close()
test_file.close()
VOC_train_file.close()
VOC_test_file.close()

執行完以後,在darknet目錄中有2007_train.txt和2007_test.txt.。VOC2007文件夾中有labels與ImageSets兩個文件夾
注意:需要修改代碼中 classes

3、下載預訓練權重

此處使用的實在coco數據集上面訓練的預訓練權重(可在官網下載其他的權重文件)

鏈接: https://pan.baidu.com/s/1QxAJEHMVTEvul7_B08CPXA 提取碼: z2up

4、修改配置文件

4.1、data/voc.names==》data/voc-head.names

裏面主要放置類別標籤名
原來內容如圖
在這裏插入圖片描述

可以先保留原來文本,重新複製重命名一份voc-head.names.內容如下
在這裏插入圖片描述
自己的類別標籤名。

4.2、cfg/voc.data==》cfg/voc-head.data

裏面主要放置:類別數目,生成的2007_train.txt與2007_test.txt位置,上面修改的voc.names位置,以及backup的位置。
原內容如下
在這裏插入圖片描述

注意:一定要按照自己的修改
voc-head.data 修改後的內容如下圖
在這裏插入圖片描述

4.3、cfg/yolov4-custom.cfg==》cfg/yolov4-head.cfg

主要是訓練的一些配置
主要修改的地方如下

  • 如下1 會影響內存的哦,內存不夠就該改改也行可以跑

batch=32
subdivisions=16
width=608
height=608
在這裏插入圖片描述

  • 如下2 最大的batches

max_batches = 5000 (一般是類別數*2000 最好不低於4000)
policy=steps
steps=4000,4500 (學習率的變化一般是總batches的80%與90%進行學習率的調整)
scales=.1,.1
在這裏插入圖片描述

  • 如下3 調整yolo標籤下的classes數與上面的convolutional標籤的filters

[convolutional]
size=1
stride=1
pad=1
filters=18 (類別數目+5)*3
activation=linear

[yolo]
mask = 3,4,5
anchors = 12, 16, 19, 36, 40, 28, 36, 75, 76, 55, 72, 146, 142, 110, 192, 243, 459, 401
classes=1 (自己的類別數)
num=9
jitter=.3
ignore_thresh = .7
truth_thresh = 1
scale_x_y = 1.1
iou_thresh=0.213
cls_normalizer=1.0
iou_normalizer=0.07
iou_loss=ciou
nms_kind=greedynms
beta_nms=0.6
max_delta=5
在這裏插入圖片描述

敲黑板:一共有三處yolo需要修改,切記、切記

5、進行訓練

確認上面的修改完成後就可以訓練了

./darknet detector train cfg/voc-head.data cfg/yolov4-head.cfg yolov4.conv.137   

或 可以顯示訓練變化的map

./darknet detector train cfg/voc-head.data cfg/yolov4-head.cfg yolov4.conv.137 -map

6、測試

6.1、修改cfg/yolov4-custom.cfg==》cfg/yolov4-head-test.cfg

修改
batch=1
subdivisions=1

6.2、進行測試

  • 圖片測試
./darknet detector test cfg/voc-head.data cfg/yolov4-head-test.cfg backup/yolov4-head_final.weights     img1.jpg
  • 視頻測試
./darknet detector demo cfg/voc-head.data cfg/yolov4-head-test.cfg backup/yolov4-head_final.weights ship.mp4

7、代碼測試

C++使用YOLOv4簡單案例

8、檢測結果

yolov4的結果
在這裏插入圖片描述
在這裏插入圖片描述

模型下載地址
訓練數據下載地址
學習的簡單記錄,方面下次使用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章