发表于 2022-1-5 10:50:07

open cv2初探人脸识别

最近学习python cv2 ,试着探究下人脸识别;
import cv2

# 2、加载图片绝对路径
image = cv2.imread(r'E:\dd\face.jpg')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
# 3、加载人脸模型
faceCascade= cv2.CascadeClassifier(r'E:\dd\cv3\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml')
faces_rects = faceCascade.detectMultiScale(image,scaleFactor = 1.05, minNeighbors = 5, minSize = (30,30), flags = cv2.CASCADE_SCALE_IMAGE)
eye_cascade = cv2.CascadeClassifier(r'E:\dd\cv3\opencv\sources\data\haarcascades\haarcascade_eye.xml')
for (x,y,w,h) in faces_rects:
    img = cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray
    roi_color = img
    eyes = eye_cascade.detectMultiScale(roi_gray)
    for (ex,ey,ew,eh) in eyes:
      cv2.rectangle(roi_color, (ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.namedWindow('image',0)   
cv2.imshow('image',image)
cv2.waitKey(0)


人脸模型是在github上https://github.com/XuBaozhao/opencv/tree/master/data/haarcascades 下载的,但在加载人脸模型时会出现bug提示
解决的方案:(1)下载https://nchc.dl.sourceforge.net/project/opencvlibrary/opencv-win/3.4.1/opencv-3.4.1-vc14_vc15.exe,放在哪里都可以(没有测试),把它解压(解压都哪里应该都可以),里面包含上述用到的两个xml文件。(2)在调用时,用绝对路径进行访问(可能也可以放到公共路径上,没有测试),如faceCascade = cv2.CascadeClassifier(r'E:\dd\cv3\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml')。
点击运 行:会出现检测到人脸;用print可打印出当前人脸的坐标位置:


页: [1]
查看完整版本: open cv2初探人脸识别