天天看點

Python + OpenCV人臉檢測

在 opencv根目錄\sources\data\haarcascades中提供了很多訓練好的分類器,我們使用haarcascade_frontalface_alt.xml分類器。

Haar cascade是Paul Viola和 Michael Jone在2001年,論文”Rapid Object Detection using a Boosted Cascade of Simple Features”提出的一種Object Detection方法。

import cv2

# 讀入圖像
img = cv2.imread("test.jpg")

# 加載人臉特征,該檔案在 python安裝目錄\Lib\site-packages\cv2\data 下
face_cascade = cv2.CascadeClassifier(r'haarcascade_frontalface_default.xml')
# 将讀取的圖像轉為COLOR_BGR2GRAY,減少計算強度
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 檢測出的人臉個數
faces = face_cascade.detectMultiScale(gray, scaleFactor = 1.15, minNeighbors = 5, minSize = (5, 5))

print("Face : {0}".format(len(faces)))

# 用矩形圈出人臉的位置
for(x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) 

cv2.namedWindow("Faces")
cv2.imshow("Faces", img)
cv2.waitKey(0)
cv2.destroyAllWindows()