OpenCv-Python-人脸检测

在opencv中有一个人脸检测(不是人脸识别)的xml文件,如下图所示:
OpenCv-Python-人脸检测
调用这个文件就可以进行人脸检测了,代码比较简单,如下:

import cv2 as cv
import numpy as np

faces_file="D:/OpenCv/opencv 4.0.0/sources/data/haarcascades/haarcascade_frontalface_alt.xml"
face_cas=cv.CascadeClassifier(faces_file)  #读取训练的文件

capture=cv.VideoCapture(0)  # 调用本机第一个摄像头

while(True):
    ret,frame=capture.read()

    cv.flip(frame,1,dst=frame)   #摄像头调换

    gray=cv.cvtColor(frame,cv.COLOR_BGR2GRAY)   #转灰度图,因为人脸检测需要灰度图
    gray = cv.equalizeHist(gray)
    t1=cv.getTickCount()
    faces=face_cas.detectMultiScale(gray,1.1,2,0,minSize=(24,24))  #人脸检测
    for (x,y,w,h) in faces:
        cv.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2,8,0)   # 绘制矩形框
    t=(cv.getTickCount()-t1)/cv.getTickFrequency()
    fps = str(1.0 / t)   # 帧率
    cv.putText(frame,'FPS:'+fps,(10,20),cv.FONT_HERSHEY_COMPLEX,0.5,(255,255,255))
    cv.imshow("output video",frame)
    c=cv.waitKey(10)
    if c==27:
        break


cv.waitKey(0)
capture.release()   # 释放视频资源
cv.destroyAllWindows()  # 销毁所有窗口,释放内存
上一篇:Otsu源码复现---python


下一篇:Paint it really, really dark gray CodeForces - 717E