自动裁剪照片为证件照

编程入门 行业动态 更新时间:2024-10-26 00:26:58

自动裁剪<a href=https://www.elefans.com/category/jswz/34/1771033.html style=照片为证件照"/>

自动裁剪照片为证件照

近期在研究如何利用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!')

更多推荐

自动裁剪照片为证件照

本文发布于:2024-02-11 14:10:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1681397.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:照片   证件照

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!