1. 程式人生 > >python用opencv批量檢測人臉,並儲存

python用opencv批量檢測人臉,並儲存

import cv2
import sys
import os
from PIL import Image
cascPath = "haarcascade_frontalface_default.xml" #訓練引數檔案
faceCascade = cv2.CascadeClassifier(cascPath)#分類器

base = 'new_dir\\'
for img in os.listdir(base):
    image = cv2.imread(base + img)#讀取圖片
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    gray = cv2.equalizeHist(gray) #直方圖均衡化,提高分類效果
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(10, 10)
    )
    num = 0
    for (x, y, w, h) in faces:
        cv2.imwrite("face_dir\\" + img,image[y:y+h,x:x+w])
        num += 1
#     cv2.imshow("Faces found", image)
    cv2.waitKey(0)