1. 程式人生 > 其它 >人臉區域識別之opencv-demo

人臉區域識別之opencv-demo

首先定義繪製圖像的函式,注意,opencv中的影象為BGR格式,與平時的RGB格式不符,所以需要在jupyternotebook中繪製的時候需要先轉化。

def cv_imshow(image):
    img_to_plot = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    plt.imshow(img_to_plot)

人臉檢測模組
利用opencv定義的api進行人臉識別任務

%%time
from  matplotlib import pyplot as plt
#圖片人臉檢測
import cv2
import sys
# Get user supplied values
imagePath = './test.jpg'
# Create the haar cascade
faceCascade = cv2.CascadeClassifier('./haarcascade_frontalface_alt2.xml') 
# Read the image
image = cv2.imread(imagePath)#2
plt.imshow(image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)#3
# Detect faces in the image
faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.15,
    minNeighbors=5,
    minSize=(5,5),
    flags = cv2.CASCADE_SCALE_IMAGE
) #4
print ('Found {} faces!'.format(len(faces)))#5
for i in faces:
    x = i[0]
    y = i[1]
    w = i[2]
    h = i[3]
    cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2) #6
cv_imshow(image)

%%time魔法函式可以計算該程式碼塊執行時間

很喜歡聽到一個老師說的“半年理論”,現在做出的努力,一般要在半年的沉澱之後,才能出結果,所以在遇到瓶頸之時,不妨再努力半年