近期在研究如何利用opencv 抓取照片中人脸的位置,自动裁剪成合适的证件照片
代码:
import numpy as np
import cv2
import os
def crop_face(input_folder_path, output_folder_path):
face_detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
images = os.listdir(input_folder_path)
for image in images:
image_path = os.path.join(input_folder_path, image)
img = cv2.imread(image_path)
height, width, channels = img.shape
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_detector.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5, minSize=(256, 256)) #确保人脸要求的最少像素是256*256
# 无法识别面部的图片
if len(faces)==0:
print(f"No face found in {image_path}")
continue
if len(faces) > 0:
# 取第一个脸部位置,这里假设一张图片只有一个脸部特征
x, y, w, h = faces[0]
# 确定最大正方形的位置
square_size=min(width-x,x,y,height-y)
# 根据最大正方形位置裁剪图片并保存
cropped_img = img[y-square_size:y+h+square_size, x-square_size:x+w+square_size] #img[y1:y2, x1:x2]
# 调整图像大小为800x800
resized = cv2.resize(cropped_img, (800, 800), interpolation=cv2.INTER_AREA)
# 计算裁边值
pad_x = (800-600) // 2
# 进行裁边处理,把照片变成600*800,符合竖直照片比例
cropped_resized = resized[:, pad_x:pad_x+600]
output_path = os.path.join(output_folder_path, image)
cv2.imwrite(output_path, cropped_resized)
if __name__ == "__main__":
input_folder = r".\input"
output_folder = r".\output"
# 创建输出目录
if not os.path.exists(output_folder):
os.makedirs(output_folder)
crop_face(input_folder, output_folder)
print('Done!')