1. 安装cv2
pip install opencv-python
2. 安装faced
使用pip默认安装的faced版本比较低,建议采用github提供的方法安装,参考 iitzco/faced: 🚀 😏 Near Real Time CPU Face detection using deep learning
pip install git+https://github.com/iitzco/faced.git
PS: 这种方式需要先安装git,如果速度太慢,可以用gitee的镜像
3. 代码
import cv2
from faced import FaceDetector
face_detector = FaceDetector()
def get_face_count(path):
'''
检测相片人脸数量
'''
img = cv2.imread(path)
rgb_img = cv2.cvtColor(img.copy(), cv2.COLOR_BGR2RGB)
# Receives RGB numpy image (HxWxC) and
# returns (x_center, y_center, width, height, prob) tuples.
faces = face_detector.predict(rgb_img, 0.85)
return len(faces)
if __name__ == '__main__':
print('face count: %d' % get_face_count('test.jpg'))
4. 错误处理
4.1 vc runtime错误
ImportError: Could not find the DLL(s) 'msvcp140.dll or msvcp140_1.dll'. TensorFlow requires that these DLLs be installed in a directory that is named in your %PATH% environment variable. You may install these DLLs by downloading "Microsoft C++ Redistributable for Visual Studio 2015, 2017 and 2019" for your platform from this URL: https://support.microsoft.com/help/2977003/the-latest-supported-visual-c-downloads
这个提示的比较明白,缺少vc runtime,按提示安装就可解决。
4.2 tensorflow错误
AttributeError: module 'tensorflow' has no attribute 'Session'. Did you mean: 'version'?
这个问题稍微麻烦,faced引用了tensorflow,装的是tensorflow 2.0版本,但语法是1.0的,导致这个报错。需要修改faced的detector.py文件,路径是python安装目录/Lib/site-packages/faced/detector.py
# 注视掉这一行
# import tensorflow as tf
# 新增这一行
import tensorflow.compat.v1 as tf