对现有图像进行检测保存:
一、代码实现
import os
import cv2
from mtcnn.mtcnn import MTCNN
outer_path = '/Users/xuqiong/AgeGender/test_img_process/Qbbre'
filelist = os.listdir(outer_path) # 列举图片
detector = MTCNN()
for item in filelist:
src = os.path.join(os.path.abspath(outer_path), item)
input_img = cv2.imread(src)
detected = detector.detect_faces(input_img)
if len(detected) > 0: # 大于0则检测到人脸
for i, d in enumerate(detected): # 单独框出每一张人脸
x1, y1, w, h = d['box']
x2 = x1 + w
y2 = y1 + h
image = input_img[(y1-10):(y2+10), (x1-10):(x2+10)]
cv2.imwrite(src, image, [int(cv2.IMWRITE_PNG_COMPRESSION), 9])
如果保存的人脸想要更多留白,可以修改:image = input_img[(y1-10):(y2+10), (x1-10):(x2+10)]中的10。
备注:
cv2.IMWRITE_JPEG_QUALITY类型为Long,必须转换成int
从0到9,压缩级别越高,图像尺寸越小
二、效果
检测保存前:
检测保存后: