@Perfect-Demo
2018-12-17T01:31:39.000000Z
字数 1227
阅读 2038
opencv+dlib
这其实也是人脸检测,达到的视觉效果和第一篇文章一样,只不过这里用的是自己训练的模型,就认为是一种扩展吧。
这里贴出训练好了的一个CNN模型链接:模型链接
下面直接上代码,代码意义注释中有解释
import cv2import sysimport dlibimport os#导入CNN模型# detector = dlib.cnn_face_detection_model_v1(mmod_human_face_detector.dat)detector = dlib.cnn_face_detection_model_v1(mmod_human_face_detector.dat)#这列用命令行的方式传入图片参数(其实就是名字)for f in sys.argv[1:]:#用opencv读取图片img = cv2.imread(f, cv2.IMREAD_COLOR)# 摘自官方文档:# image is a numpy ndarray containing either an 8bit grayscale or RGB image.# opencv读入的图片默认是bgr格式,我们需要将其转换为rgb格式;都是numpy的ndarray类。b, g, r = cv2.split(img) #分离是三颜色通道img = cv2.merge([r, g, b]) #把三种颜色组合成rgb新图片dets = detector(img, 1) #调用dlib库对图片进行识别print("这张图识别到 {} 张人脸".format(len(dets)))for index, face in enumerate(dets):#left()、top()、right()、bottom()都是dlib.rectangle类的方法,对应矩形四条边的位置print("人脸{}的框位置为left:{} , top:{} , right:{} , bottom{}".format(index, face.left(), face.top(), face.right(), face.bottom()))#在图片中标注并显示left = face.left()top = face.top()right = face.right()bottom = face.bottom()bottom = face.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版本过旧问题,出现没法用dlib.cnn_face_detection_model_v1()方法导入模型的情况。所以这里可能需要装个新版本。