openCV+python实现人脸实时检测

系统 1904 0

 

一、静态的图像人脸检测

            
              import numpy as np
import cv2 as cv

path = 'haarcascade_frontalface_default.xml'
face_cascade = cv.CascadeClassifier(path)
path = 'haarcascade_eye.xml'
eye_cascade = cv.CascadeClassifier(path)


# 静态图像人脸检测
img = cv.imread('test.jpg')
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)


faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
    cv.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
    eyes = eye_cascade.detectMultiScale(roi_gray)
    for (ex,ey,ew,eh) in eyes:
        cv.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv.imshow('img',img)
cv.waitKey(0)
cv.destroyAllWindows()
            
          

 

二、视频人脸实时检测及保存

 

            
              # 摄像头动态人脸检测 及 视频保存

import numpy as np
import cv2 as cv


path = 'haarcascade_frontalface_default.xml'
face_cascade = cv.CascadeClassifier(path)
path = 'haarcascade_eye.xml'
eye_cascade = cv.CascadeClassifier(path)


#1.来自视频图像
# cap = cv.VideoCapture('/Users/admin/opencv-4.0.0/samples/data/vtest.avi')
#2. 来自摄像头
cap = cv.VideoCapture(0)
print(cap.isOpened())
count = 0


# 视频保存的参数设置
sz = (int(cap.get(cv.CAP_PROP_FRAME_WIDTH)),
        int(cap.get(cv.CAP_PROP_FRAME_HEIGHT)))
fps = 5
#fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
#fourcc = cv2.VideoWriter_fourcc('m', 'p', 'e', 'g')
fourcc = cv.VideoWriter_fourcc(*'mpeg')
## open and set props
vout = cv.VideoWriter()
vout.open('output2.mp4',fourcc,fps,sz,True)
 

while(True):
    count += 1
    ret, img = cap.read()
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
#     cv.imshow('FRAME', gray)
#     cv.imwrite('FRAME_%d.png'%count, gray)
    
    
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        cv.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]
        eyes = eye_cascade.detectMultiScale(roi_gray)
        for (ex,ey,ew,eh) in eyes:
            cv.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,255),2)
    cv.imshow('img',img)
    vout.write(img)
    
    
    if cv.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
vout.release()
cv.destroyAllWindows()
            
          

 


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论