1. 程式人生 > >Python使用opencv做人臉識別

Python使用opencv做人臉識別

1、安裝opencv-python

pip install opencv-python

2、下載haarcascades

https://github.com/opencv/opencv/tree/master/data/haarcascades

目錄下的特徵分類器的xml檔案。

3、使用opencv做人臉識別的程式碼

import cv2

# 引入人像識別訓練庫 haarcascade_frontalface_default.xml
face_patterns = cv2.CascadeClassifier('/Users/hepburn/opencv-master/data/haarcascades/haarcascade_frontalface_default.xml')
# 讀取圖片
sample_image = cv2.imread('/Users/hepburn/Python/FaceRecognize/test.jpg')
# 獲取識別到的人臉
faces = face_patterns.detectMultiScale(sample_image,scaleFactor=1.1,minNeighbors=4,minSize=(40, 40))
# 將識別到的人臉框出來
for (x, y, w, h) in faces:
    cv2.rectangle(sample_image, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 生成一張新的圖片儲存識別結果
cv2.imwrite('/Users/hepburn/Python/FaceRecognize/output_detected.png', sample_image);