如何从中心裁剪具有特定尺寸的图像?

How to crop an image from the center with certain dimensions?

假设我们有一张具有以下尺寸的图像:

width = 200
height = 100

假设我们的裁剪尺寸为 50x50

如何使用 Python 从图像的 中心 使用这个新维度裁剪图像?

假设裁剪框的尺寸为:cw, ch = 50, 50

图像的中心是点 (w//2, h//2),其中 w 是它的宽度,h 是它的高度。边长为 50 像素的方形裁剪框也将在那里居中。

这意味着裁剪框的左上角在 (w//2 - cw//2, h//2 - ch//2),右下角在 (w//2 + cw//2, h//2 + ch//2)

至少有 两种 我能想到的裁剪图像的方法。第一种是使用 Image.crop() 方法并将矩形裁剪区域的坐标传递给它。

box = w//2 - cw//2, h//2 - ch//2, w//2 + cw//2, h//2 + ch//2
cropped_img = img.crop(box)

可以在数学上简化以减少划分的数量:

box = (w-cw)//2, (h-ch)//2, (w+cw)//2, (h+ch)//2  # left, upper, right, lower
cropped_img = img.crop(box)

另一种方法是通过 ImageOps.crop() 函数,该函数传递四个边中每一边的边框大小:

from PIL import ImageOps

wdif, hdif = (w-cw)//2, (h-ch)//2
border = wdif, hdif, wdif, hdif  # left, top, right, bottom
cropped_img = ImageOps.crop(img, border)