python3 -m pip install opencv-contrib-python Collecting opencv-contrib-python Downloading https://pypi.tuna.tsing Successfully installed opencv-contrib-python-4.7.0.72.../opencv_contrib_python-4.7.0.72-cp37-abi3-win_amd64.whl (44.9 MB)
下方是检测人脸的程序代码如下。其中haarcascade_frontalface_default.xml为检测人脸的算法文件,可到opencv官方github地址中 https://github.com/opencv/opencv/tree/master/data/haarcascades 下载。上面有非常多的人脸算法。本文地址:http://api.04007.cn/article/1222.html,未经许可,不得转载.
import cv2 import os def generate_img(dirname): # 显示当前目录,好排查相关文件加载、图片保存的路径问题 print(os.getcwd()) face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') if (not os.path.isdir(dirname)): os.makedirs(dirname) cap = cv2.VideoCapture(0) count = 0 while True: ret,frame = cap.read() x,y = frame.shape[0:2] small_frame = cv2.resize(frame, (int(y/2), int(x/2))) result = small_frame.copy() gray = cv2.cvtColor(small_frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray,1.3,5) for (x, y, w, h) in faces: result = cv2.rectangle(result, (x, y), (x + w, y + h), (255, 0, 0), 2) f = cv2.resize(gray[y: y + h, x: x + w], (200, 200)) if count <= 10: cv2.imwrite(dirname + '%s.png' % str(count), f) count += 1 cv2.imshow('face', result) if cv2.waitKey(40) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() if __name__ == '__main__': generate_img("./saveimg/")在使用opencv haarcascade_frontalface_default.xml识别人脸的时候,发现其性能比较高,可以直接在我基于CPU的电脑上流畅运行,并尝试了使用一些照片,发现只有照片离摄像头足够近时才可以检测到人脸。另外体验中发现它对于旋转人脸、非正面人脸识别效果不太好,特别是当使用手挡住眼睛后会直接导致人脸检测失败,应该是采用的传统机器学习算法。本文地址:http://api.04007.cn/article/1222.html,未经许可,不得转载.
本文地址:http://api.04007.cn/article/1222.html 未经许可,不得转载. 手机访问本页请扫描右下方二维码.
![]() |
![]() |
手机扫码直接打开本页面 |