You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按3:4比例围绕检测到的人脸居中裁剪800x800图片

实现人脸居中的3:4比例裁剪方案

核心思路

  1. 计算检测到的人脸区域中心点
  2. 按照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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 09:25:11