自动裁剪照片为证件照
近期在研究如何利用opencv 抓取照片中人脸的位置,自动裁剪成合适的证件照片
代码:
import numpy as np
import cv2
import osdef 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.shapegray = 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}")continueif 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]# 调整图像大小为800x800resized = 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!')
自动裁剪照片为证件照
近期在研究如何利用opencv 抓取照片中人脸的位置,自动裁剪成合适的证件照片
代码:
import numpy as np
import cv2
import osdef 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.shapegray = 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}")continueif 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]# 调整图像大小为800x800resized = 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!')
发布评论