1. 程式人生 > >opencv(11)-人臉檢測

opencv(11)-人臉檢測

人臉檢測

Haar級聯實現人臉檢測:

靜態影象:

程式碼:

import cv2
import numpy as np

file_path = './cascades/haarcascade_frontalface_default.xml'

# 人臉檢測
def detect_face(src,file_path):
    face_cascade = cv2.CascadeClassifier(file_path) # 負責人臉檢測
    gray = cv2.cvtColor(src,cv2.COLOR_BGR2GRAY)
    # detectMultiScale(image[, scaleFactor[, minNeighbors[, flags[, minSize[, maxSize]]]]]) -> objects
    faces = face_cascade.detectMultiScale(gray,1.3,5)# 1 gray 2 每次迭代時影象的壓縮率 3 每個人臉矩形保留近鄰數目的最小值
    
    for (x,y,w,h) in faces:
        img = cv2.rectangle(src,(x,y),(x+w,y+h),(0,0,255),2)
    cv2.imshow('face',img)

img = cv2.imread('test.jpg',1)
detect_face(img,file_path)
cv2.waitKey(0)
cv2.destroyAllWindows()    

結果:

視訊影象:

程式碼:

import cv2
import numpy as np

file_face_path_input = './cascades/haarcascade_frontalface_default.xml'
file_eye_path_input = './cascades/haarcascade_eye.xml'

# 人臉檢測
def detect_face(src,file_face_path,file_eye_path):
    face_cascade = cv2.CascadeClassifier(file_face_path) # 負責人臉檢測
    eye_cascade = cv2.CascadeClassifier(file_eye_path) # 負責人眼檢測
    gray = cv2.cvtColor(src,cv2.COLOR_BGR2GRAY)
    # detectMultiScale(image[, scaleFactor[, minNeighbors[, flags[, minSize[, maxSize]]]]]) -> objects
    faces = face_cascade.detectMultiScale(gray,1.03,5)# 1 gray 2 每次迭代時影象的壓縮率 3 每個人臉矩形保留近鄰數目的最小值
    
    for (x,y,w,h) in faces:
        cv2.rectangle(src,(x,y),(x+w,y+h),(0,0,255),2)
        eye_gray = gray[y:y+h,x:x+w]
        eyes = eye_cascade.detectMultiScale(eye_gray,1.03,5,0,(40,40))
        for (ex,ey,ew,eh) in eyes:
            cv2.rectangle(src,(ex,ey),(ex+ew,ey+eh),(255,0,0),2)
    cv2.imshow('result',src)

video_capture = cv2.VideoCapture(0)
while True:
    ret,frame = video_capture.read()
    frame = cv2.flip(frame,1)
    detect_face(frame,file_face_path_input,file_eye_path_input)
    c = cv2.waitKey(10)
    if c==27:
        break