一、图片人脸检测(opencv)
1、安装opencv环境
介绍windows中opencv在python3上的实现,我的系统环境win10+python3.6+opcv3.4.1
首先去网站下载OpenCV对应的.whl版本压缩包,网址:https://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv 本人下载的版本是:opencv_python‑3.4.1‑cp36‑cp36m‑win_amd64.whl 64位系统对应python3.6的,下载到F盘根目录。
链接:百度云链接
提取码:j5uy
接着用pip命令安装
pip install F:\opencv_python-3.4.1-cp36-cp36m-win_amd64.whl
当命令行窗口显示:
Processing F:\opencv_python-3.4.1-cp36-cp36m-win_amd64.whl
Installing collected packages: opencv-python
Successfully installed opencv-python-3.4.1
说明已经安装成功。
到此,opencv的环境配置已经弄好了,可以在命令行中运行python,然后import cv2 打印输出opencv的版本号,看能否正常输出。
2、具体实现代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import cv2
img = cv2.imread('img/1.png') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
classifier = cv2.CascadeClassifier(r'F:\python-project\opencv-master\haarcascade_frontalface_default.xml') color = (0, 255, 0)
faceRects = classifier.detectMultiScale( gray, scaleFactor=1.2, minNeighbors=3, minSize=(24, 24))
if len(faceRects): for faceRect in faceRects: x, y, w, h = faceRect cv2.rectangle(img, (x, y), (x + h, y + w), color, 2) cv2.rectangle(img, (x + 3 * w // 8, y + 3 * h // 4), (x + 5 * w // 8, y + 7 * h // 8), color)
cv2.imshow("image-detection", img)
cv2.waitKey(0) cv2.destroyAllWindows()
|
3、识别结果
二、图片人脸检测(dlib)
比opencv更加精准的图片人脸检测库Dlib,Dlib可以检测脸部68甚至更多的特征点。
1、安装dlib
下载地址:https://pypi.org/simple/dlib/
我的环境为win10+python3.6.5
选择dlib的版本为:dlib-19.8.1-cp36-cp36m-win_amd64.whl
接着用pip命令安装:
pip install dlib-19.8.1-cp36-cp36m-win_amd64.whl
2、训练模型
下载链接:https://pan.baidu.com/s/1xai1X_L8JvDfFJyU3f_0Ig
提取码:g24q
3、具体实现代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import cv2 import dlib
path = "img/1.png" img = cv2.imread(path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor( "F:\\python-project\\shape_predictor_68_face_landmarks.dat" )
dets = detector(gray, 1) for face in dets: shape = predictor(img, face) for pt in shape.parts(): pt_pos = (pt.x, pt.y) cv2.circle(img, pt_pos, 2, (0, 255, 0), 1) cv2.imshow("image", img)
cv2.waitKey(0) cv2.destroyAllWindows()
|
4、识别结果
参考链接:https://github.com/vipstone/faceai/blob/master/doc/detectionOpenCV.md