[关闭]
@Perfect-Demo 2018-12-17T01:31:39.000000Z 字数 1227 阅读 1890

(3)将训练好的CNN模型用于dlib

opencv+dlib


这其实也是人脸检测,达到的视觉效果和第一篇文章一样,只不过这里用的是自己训练的模型,就认为是一种扩展吧。
这里贴出训练好了的一个CNN模型链接:模型链接
下面直接上代码,代码意义注释中有解释

  1. import cv2
  2. import sys
  3. import dlib
  4. import os
  5. #导入CNN模型
  6. # detector = dlib.cnn_face_detection_model_v1(mmod_human_face_detector.dat)
  7. detector = dlib.cnn_face_detection_model_v1(mmod_human_face_detector.dat)
  8. #这列用命令行的方式传入图片参数(其实就是名字)
  9. for f in sys.argv[1:]:
  10. #用opencv读取图片
  11. img = cv2.imread(f, cv2.IMREAD_COLOR)
  12. # 摘自官方文档:
  13. # image is a numpy ndarray containing either an 8bit grayscale or RGB image.
  14. # opencv读入的图片默认是bgr格式,我们需要将其转换为rgb格式;都是numpy的ndarray类。
  15. b, g, r = cv2.split(img) #分离是三颜色通道
  16. img = cv2.merge([r, g, b]) #把三种颜色组合成rgb新图片
  17. dets = detector(img, 1) #调用dlib库对图片进行识别
  18. print("这张图识别到 {} 张人脸".format(len(dets)))
  19. for index, face in enumerate(dets):
  20. #left()、top()、right()、bottom()都是dlib.rectangle类的方法,对应矩形四条边的位置
  21. print("人脸{}的框位置为left:{} , top:{} , right:{} , bottom{}".format(index, face.left(), face.top(), face.right(), face.bottom()))
  22. #在图片中标注并显示
  23. left = face.left()
  24. top = face.top()
  25. right = face.right()
  26. bottom = face.bottom()
  27. bottom = face.bottom()
  28. cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 3)
  29. cv2.namedWindow(f, cv2.WINDOW_AUTOSIZE)
  30. cv2.imshow(f, img)
  31. # 等待按键,随后退出,销毁窗口
  32. k = cv2.waitKey(0)
  33. cv2.destroyAllWindows()

效果与第一篇人脸检测一样。

但是注意可能会由于dlib版本过旧问题,出现没法用dlib.cnn_face_detection_model_v1()方法导入模型的情况。所以这里可能需要装个新版本。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注