基于dlib的物体检测(转)

原文出处: http://xugaoxiang.com/post/124

软硬件环境

  • ubuntu 18.04 64bit
  • dlib
  • opencv
  • python2

准备dlib环境

pip install dlib

imglab工具安装

git clone https://github.com/davisking/dlib
cd dlib/tools/imglab
mkdir build
cd build
cmake ..
cmake --build . --config Release
sudo make install

素材准备

把所有要训练的汽车图片保存到car_train文件夹,要测试的图片放到car_test文件夹,2个文件夹里的图片不要一样,以免影响测试效果

cd car_train
imglab -c car.xml .
imglab car.xml

打标签的方法很简单,在imglab窗口下,先按住shift键,然后在车身的左上方按下鼠标左键,拖动到车身右下方再放开鼠标,这样就在车身位置上画出了一个矩形框,如下图所示

基于dlib的物体检测(转)_第1张图片

针对每一张图片进行上述操作,结束后保存。如果数据集够大的话,确实是个体力活。

训练代码

#!/usr/bin/env python2

# -*- coding: utf-8 -*-

import os
import dlib

# 训练的参数,可以根据实际情况进行修改
options = dlib.simple_object_detector_training_options()

options.add_left_right_image_flips = True
options.C = 5
options.num_threads = 4
options.be_verbose = True


current_path = os.getcwd()
train_folder = current_path + '/car_train/'
train_xml_path = train_folder + 'car.xml'

print("start training:")

# 最重要的一个函数
dlib.train_simple_object_detector(train_xml_path, 'detector.svm', options)

print("Training accuracy: {}".format(
    dlib.test_simple_object_detector(train_xml_path, "detector.svm")))

检测代码

#!/usr/bin/env python2

# -*- coding: utf-8 -*-

import os
import sys
import dlib
import cv2
import glob

detector = dlib.simple_object_detector("detector.svm")

current_path = os.getcwd()
test_folder = current_path + '/car_test/'

for f in glob.glob(test_folder+'*.jpg'):
    print("Processing file: {}".format(f))
    img = cv2.imread(f, cv2.IMREAD_COLOR)
    b, g, r = cv2.split(img)
    img2 = cv2.merge([r, g, b])
    dets = detector(img2)
    print("Number of cars detected: {}".format(len(dets)))
    for index, car in enumerate(dets):
        print('car {}; left {}; top {}; right {}; bottom {}'.format(index, car.left(), car.top(), car.right(), car.bottom()))

        left = car.left()
        top = car.top()
        right = car.right()
        bottom = car.bottom()
        cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 3)
        cv2.namedWindow(f, cv2.WINDOW_AUTOSIZE)
        cv2.imshow(f, img)

k = cv2.waitKey(0)
cv2.destroyAllWindows()

 

小结

根据上述方法,对于一般的物体检测都可以用dlib来实现,你可以训练猫,也可以训练狗,等等等等,感兴趣的话,都来试试吧。

参考资料

  • https://github.com/davisking/dlib
  • https://blog.csdn.net/hongbin_xu/article/details/78443289
  • http://www.hackevolve.com/create-your-own-object-detector/
  • http://dlib.net/train_object_detector.cpp.html

 

你可能感兴趣的:(DLIB)