2.1使用opencv的人脸检测#!/usr/bin/env python#-*- coding:utf-8-*-
importosimportos.path as ospimportcv2importglobfrom io_helper import *cv_root= 'D:/install packages/opencv-3.4.2/data/haarcascades'cv_face_model_path= cv_root + '/haarcascade_frontalface_alt2.xml'cv_face_model_path2= cv_root + '/haarcascade_profileface.xml'
deftest_face_detect_cv():
classifier1= cv2.CascadeClassifier(cv_face_model_path) #正脸
filepath = ''img= cv2.imread(filepath) #读取图片
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #转换灰色
faceRects =classifier1.detectMultiScale(gray,
scaleFactor=1.1,
minNeighbors=1,
minSize=(10, 10))if len(faceRects): #大于0则检测到人脸
for box in faceRects: #单独框出每一张人脸
x, y, w, h =box
cv2.rectangle(img, (x, y), (x+ w, y + h), (0, 0, 255), 1)
cv2.imshow('a', img)
cv2.waitKey(0)
cv2.destroyAllWindows()defface_detect_save():
path= r'D:/AI/DataSet/emotion/fer2013/train_class'files= glob.glob(path + '/**/*.jpg')
new_dir= path + '/cut_face'new_dir2= path + '/no_face'mkdir_if_not_exist(new_dir)
mkdir_if_not_exist(new_dir2)#OpenCV人脸识别分类器
classifier1 = cv2.CascadeClassifier(cv_face_model_path) #正脸
#classifier2 = cv2.CascadeClassifier(cv_face_model_path2) # 侧脸
for filepath infiles:
chd_dir= new_dir + '/' + filepath.split('\\')[-2]
mkdir_if_not_exist(chd_dir)
chd_dir2= new_dir2 + '/' + filepath.split('\\')[-2]
mkdir_if_not_exist(chd_dir2)
filename=osp.basename(filepath)
img= cv2.imread(filepath) #读取图片
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #转换灰色
color = (0, 255, 0) #定义绘制颜色
#调用识别 正脸人脸
faceRects =classifier1.detectMultiScale(gray,
scaleFactor=1.1,
minNeighbors=1,
minSize=(10, 10))iflen(faceRects):for box in faceRects: #单独框出每一张人脸
x, y, w, h =box
face_roi= img[y:y + h, x:x +w, :]
file= chd_dir + '/' +filename
cv2.imwrite(file,face_roi)else:
file= chd_dir2 + '/' +filename
shutil.copy(filepath,file)print('work is done .')if __name__ == '__main__':
face_detect_save()2.2使用mtcnn的包进行人脸检测
-----------------------------------------
使用python公开包 mtcnn 来进行人脸检测和关键点检测
pip install-i https://pypi.tuna.tsinghua.edu.cn/simple mtcnn