opencv-python人脸识别初探

版权声明:本文为博主原创文章,博主欢迎各位转载。 https://blog.csdn.net/tuwenqi2013/article/details/80106722

推荐博文:

1、《浅析人脸检测之Haar分类器方法》

2、《目标检测的图像特征提取之(三)Haar特征》

3、《Face Recognition with Python》

代码:

import cv2
import sys

# Get user supplied values
imagePath = 'test.png'   # sys.argv[1]
cascPath = "haarcascade_frontalface_default.xml" #训练后的分类器

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)

# Read the image
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Detect faces in the image
faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.2, #比例因子
    minNeighbors=2,  #最小邻脸数
    minSize=(30, 30) #窗口大小
    #flags = cv2.CV_HAAR_SCALE_IMAGE
)

print("Found {0} faces!".format(len(faces)))

# Draw a rectangle around the faces
for (x, y, w, h) in faces:
    cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

cv2.imshow("Faces found", image)
cv2.waitKey(0)



效果:




修改成实时人脸识别模式(有点容易误判)

代码:

import cv2
import sys
import numpy as np

# Get user supplied values
cap =cv2.VideoCapture(0)   # sys.argv[1]
cascPath = "haarcascade_frontalface_default.xml" #训练后的分类器

# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
while(True):
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.1, #比例因子
    minNeighbors=3,  #最小邻距
    minSize=(30, 30) #窗口大小
    )
    print("Found {0} faces!".format(len(faces)))
    for (x, y, w, h) in faces:
        cv2.rectangle( frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
    cv2.imshow("Faces found",  frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

效果:



代码链接:https://github.com/gooddestiny/opencv

猜你喜欢

转载自blog.csdn.net/tuwenqi2013/article/details/80106722