7人脸识别

1图片静态识别

import cv2 as cv
import numpy as np


def face_deftect_demo():
    #转化为灰度图
    gray =cv.cvtColor(src,cv.COLOR_BGR2GRAY)
    #加载特征数据
    face_detector = cv.CascadeClassifier(  "D:/sofeware/sofeware/python37/Lib/site-packages/cv2/data/haarcascade_frontalface_alt_tree.xml")
    #在多个尺度空间进行检测(图像名,向上或者向下变换尺度值(原图几倍),变换图清晰度低选择低的值,调整1.02为1.1可以加快速度)
    faces = face_detector.detectMultiScale(gray, 1.02, 2)
    #绘制矩形,提取长宽高,设置线的颜色,宽度
    for x, y, w, h in faces:
        cv.rectangle(src, (x, y), (x+w, y+h), (0, 0, 255), 2)
    cv.imshow("result", src)


print("--------- Python OpenCV Tutorial ---------")
src = cv.imread("C:/Users/wml/Desktop/wml/ym.jpg")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.namedWindow("result", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
face_deftect_demo()
cv.waitKey(0)
cv.destroyAllWindows()

2视频动态识别

import cv2 as cv
import numpy as np
def face_deftect_demo(image):
    gray =cv.cvtColor(image,cv.COLOR_BGR2GRAY)
    face_detector = cv.CascadeClassifier(  "D:/sofeware/sofeware/python37/Lib/site-packages/cv2/data/haarcascade_frontalface_alt_tree.xml")
    faces = face_detector.detectMultiScale(gray, 1.02, 1)
    for x, y, w, h in faces:
        cv.rectangle(image, (x, y), (x+w, y+h), (0, 0, 255), 2)
    cv.imshow("result", image)


print("--------- Python OpenCV Tutorial ---------")
capture = cv.VideoCapture(0)
cv.namedWindow("result", cv.WINDOW_AUTOSIZE)
while(True):
    ret, frame = capture.read()
    frame = cv.flip(frame, 1)#镜像变换
    face_deftect_demo(frame)
    c=cv.waitKey(10)
    if(c==27):#esc停止执行
        break
# cv.imshow("input image", src)
# face_deftect_demo()
cv.waitKey(0)
cv.destroyAllWindows()

相关推荐