openCV+python實現人臉實時檢測

 

一、靜態的圖像人臉檢測

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()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章