自动裁剪照片为证件照

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值