python静态图片人脸识别。
对图片进行人脸、人眼识别,并标识出人脸、人眼的矩形区域。
安装相关库。
安装opencv-python库:pip install opencv-python
。
项目目录:
# 示例图片(/imgs/zhangjie.jpeg):
参考代码:
demo.py
import cv2 as cv
def detect(img):
classifier = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_frontalface_default.xml') # 人脸检测
classifier2 = cv.CascadeClassifier(cv.data.haarcascades + 'haarcascade_eye.xml') # 人眼检测
grayed = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
face = classifier.detectMultiScale(grayed) # 返回识别人脸的区域位置
for x, y, w, h in face: # 坐标及宽度高度
cv.rectangle(img, (x, y), (x + w, y + h), color=(0, 255, 0), thickness=2) # 画出人脸识别的矩形区域
# img所画图片,坐标,颜色,宽度
imgeye = img[y:y + h, x:x + w]
eye = classifier2.detectMultiScale(imgeye, 1.3, 10) # 返回识别人眼的区域位置
for ex, ey, ew, eh in eye:
cv.rectangle(imgeye, (ex, ey), (ex + ew, ey + eh), color=(0, 255, 255), thickness=2)# 画出人眼识别的矩形区域
# 显示
cv.imshow('result', img)
cv.waitKey(0)
cv.destroyAllWindows()
if __name__ == '__main__':
detect(cv.imread('imgs/zhangjie.jpeg'))
运行结果 :
识别成功!!!