基于dlib的物体检测

/

软硬件环境

  • ubuntu 18.04 64bit
  • dlib
  • opencv
  • python2

准备dlib环境

  1. pip install dlib

imglab工具安装

  1. git clone https://github.com/davisking/dlib
  2. cd dlib/tools/imglab
  3. mkdir build
  4. cd build
  5. cmake ..
  6. cmake --build . --config Release
  7. sudo make install

素材准备

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

  1. cd car_train
  2. imglab -c car.xml .
  3. imglab car.xml

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

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

训练代码

  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3. import os
  4. import dlib
  5. # 训练的参数,可以根据实际情况进行修改
  6. options = dlib.simple_object_detector_training_options()
  7. options.add_left_right_image_flips = True
  8. options.C = 5
  9. options.num_threads = 4
  10. options.be_verbose = True
  11. current_path = os.getcwd()
  12. train_folder = current_path + '/car_train/'
  13. train_xml_path = train_folder + 'car.xml'
  14. print("start training:")
  15. # 最重要的一个函数
  16. dlib.train_simple_object_detector(train_xml_path, 'detector.svm', options)
  17. print("Training accuracy: {}".format(
  18. dlib.test_simple_object_detector(train_xml_path, "detector.svm")))

检测代码

  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3. import os
  4. import sys
  5. import dlib
  6. import cv2
  7. import glob
  8. detector = dlib.simple_object_detector("detector.svm")
  9. current_path = os.getcwd()
  10. test_folder = current_path + '/car_test/'
  11. for f in glob.glob(test_folder+'*.jpg'):
  12. print("Processing file: {}".format(f))
  13. img = cv2.imread(f, cv2.IMREAD_COLOR)
  14. b, g, r = cv2.split(img)
  15. img2 = cv2.merge([r, g, b])
  16. dets = detector(img2)
  17. print("Number of cars detected: {}".format(len(dets)))
  18. for index, car in enumerate(dets):
  19. print('car {}; left {}; top {}; right {}; bottom {}'.format(index, car.left(), car.top(), car.right(), car.bottom()))
  20. left = car.left()
  21. top = car.top()
  22. right = car.right()
  23. bottom = car.bottom()
  24. cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 3)
  25. cv2.namedWindow(f, cv2.WINDOW_AUTOSIZE)
  26. cv2.imshow(f, img)
  27. k = cv2.waitKey(0)
  28. cv2.destroyAllWindows()

小结

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

参考资料

转载请注明作者和出处,并添加本页链接。
原文链接: blog.xugaoxiang.com/124

给我留言