如何按3:4比例围绕检测到的人脸居中裁剪800x800图片
实现人脸居中的3:4比例裁剪方案
核心思路
- 计算检测到的人脸区域中心点
- 按照3:4的宽高比确定裁剪框尺寸
- 调整裁剪框位置,确保以人脸中心为基准且不超出原图边界
- 执行裁剪并输出结果
完整代码
import numpy as np from PIL import Image from io import BytesIO # 读取原图 img = Image.open(BytesIO(image.content)) img_width, img_height = img.size # 当前为800x800 # 人脸检测得到的坐标(用户已通过其他模型获取) # top, bottom, left, right = ... # 计算人脸中心点 face_center_x = (left + right) / 2 face_center_y = (top + bottom) / 2 # 设定3:4的宽高比(宽/高) aspect_ratio = 3 / 4 # 确定符合比例的最大裁剪框尺寸(不超出原图) crop_height = img_height crop_width = crop_height * aspect_ratio if crop_width > img_width: crop_width = img_width crop_height = crop_width / aspect_ratio # 计算裁剪框的初始坐标 crop_left = face_center_x - crop_width / 2 crop_top = face_center_y - crop_height / 2 crop_right = face_center_x + crop_width / 2 crop_bottom = face_center_y + crop_height / 2 # 修正裁剪框,确保不越界 crop_left = max(0, crop_left) crop_top = max(0, crop_top) crop_right = min(img_width, crop_right) crop_bottom = min(img_height, crop_bottom) # 转换为整数(PIL裁剪需要整数坐标) crop_left = int(round(crop_left)) crop_top = int(round(crop_top)) crop_right = int(round(crop_right)) crop_bottom = int(round(crop_bottom)) # 执行裁剪 cropped_img = img.crop((crop_left, crop_top, crop_right, crop_bottom)) # 可选:转为numpy数组后续处理 cropped_np = np.array(cropped_img) # 显示结果 cropped_img.show()
代码说明
- 人脸中心点计算:通过人脸区域的左右、上下坐标取平均值,确保裁剪框以人脸为中心。
- 裁剪框尺寸适配:优先尝试以原图高度为准计算3:4比例的宽度,若宽度超出原图则改用原图宽度推导高度,保证裁剪框是符合比例的最大可行尺寸。
- 边界修正:将裁剪框坐标限制在原图范围内,避免越界报错。
- PIL裁剪:使用PIL原生的
crop()方法处理,比numpy切片更直观且不易出错。
内容的提问来源于stack exchange,提问作者Harry Lincoln
相关产品推荐
相关产品推荐

