# -*-coding:utf8-*-#import osimport cv2from PIL import Image, ImageDrawfrom datetime import datetime"""分类器 https://github.com/opencv/opencv/tree/master/data/haarcascades安装模块:pip install Pillow pip install opencv-python博客:https://blog.52itstyle.vip/archives/3771/"""def detectFaces(image_name): img = cv2.imread(image_name) face_cascade = cv2.CascadeClassifier(os.getcwd()+"//haarcascade//haarcascade_frontalface_alt.xml") if img.ndim == 3: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) else: gray = img # if语句:如果img维度为3,说明不是灰度图,先转化为灰度图gray,如果不为3,也就是2,原图就是灰度图 faces = face_cascade.detectMultiScale(gray, 1.2, 5) # 1.3和5是特征的最小、最大检测窗口,它改变检测结果也会改变 result = [] for (x, y, width, height) in faces: result.append((x, y, x + width, y + height)) return result# 保存人脸图def saveFaces(image_name): faces = detectFaces(image_name) if faces: # 将人脸保存在save_dir目录下。 # Image模块:Image.open获取图像句柄,crop剪切图像(剪切的区域就是detectFaces返回的坐标),save保存。 save_dir = image_name.split('.')[0] + "_faces" os.mkdir(save_dir) count = 0 for (x1, y1, x2, y2) in faces: file_name = os.path.join(save_dir, str(count) + ".jpg") Image.open(image_name).crop((x1, y1, x2, y2)).save(file_name) count += 1if __name__ == '__main__': time1 = datetime.now() result = detectFaces(os.getcwd()+"//images//gaoyuanyuan.jpg") time2 = datetime.now() print("耗时:" + str(time2 - time1)) if len(result) > 0: print("有人存在!!---》人数为:" + str(len(result))) else: print('视频图像中无人!!') drawFaces(os.getcwd()+"//images//", "hanxue.jpg") saveFaces(os.getcwd()+//images//gaoyuanyuan.jpg)