|
|
# coding:utf-8
|
|
|
import cv2
|
|
|
import matplotlib.pyplot as plt
|
|
|
import os
|
|
|
|
|
|
_currentFilePath = os.path.split(os.path.realpath(__file__))[0]
|
|
|
|
|
|
|
|
|
#opencv人脸检测分类器,可以进行更换,请根据左侧分类器选择你想用的填写其中
|
|
|
############### Begin #############
|
|
|
|
|
|
classifierFileName = "haarcascade_frontalface_alt.xml"
|
|
|
face_cascade = cv2.CascadeClassifier(os.path.join(_currentFilePath, classifierFileName))
|
|
|
|
|
|
############### End #############
|
|
|
|
|
|
# 读取图片
|
|
|
def read_directory(directory_name):
|
|
|
_cnt = 0
|
|
|
|
|
|
for filename in os.listdir(directory_name):
|
|
|
|
|
|
if filename.lower().endswith(".png") is False and filename.lower().endswith(".jpg") is False:
|
|
|
continue
|
|
|
|
|
|
_pathToFile = directory_name + "/" + filename
|
|
|
|
|
|
image = cv2.imread(_pathToFile)
|
|
|
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
|
|
# 探测图片中的人脸
|
|
|
faces = face_cascade.detectMultiScale(
|
|
|
gray,
|
|
|
scaleFactor=1.15,
|
|
|
minNeighbors=5,
|
|
|
minSize=(5, 5),
|
|
|
flags=cv2.CASCADE_SCALE_IMAGE)
|
|
|
|
|
|
for (x, y, w, h) in faces:
|
|
|
cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)#直接在源操作了
|
|
|
|
|
|
if len(faces) == 0:
|
|
|
print('未检测出人脸')
|
|
|
else:
|
|
|
_pathToSavedFile = os.path.join(_currentFilePath, "./images/result/") + filename + ".rst.jpg"
|
|
|
cv2.imwrite(_pathToSavedFile, image)
|
|
|
print("生成结果成功!", _pathToSavedFile)
|
|
|
print('检测到%d张人脸' % len(faces))
|
|
|
print('检测成功!')
|
|
|
_cnt = _cnt + 1
|
|
|
|
|
|
if _cnt == 0:
|
|
|
print("检测失败!")
|
|
|
|
|
|
read_directory(os.path.join(_currentFilePath, "images/source"))
|