【问题标题】:How to crop an image from the center with certain dimensions?如何从中心裁剪具有特定尺寸的图像?
【发布时间】:2018-04-07 05:35:54
【问题描述】:

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

width = 200
height = 100

假设我们作物的尺寸是50x50

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

【问题讨论】:

标签: python python-imaging-library crop


【解决方案1】:

假设裁剪框的尺寸为: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)

【讨论】:

  • 很好的答案!只是一个快速的问题。为什么我们要把 50 除以 2 (50//2)?谢谢。
  • @Simplicity:是50//2,因为裁剪框的宽度和高度为 50 像素的一半。它是 ½,因为盒子居中,所以它的大部分位于该中点的两侧。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
  • 1970-01-01
  • 2014-08-06
  • 1970-01-01
  • 2012-12-17
  • 2012-07-24
相关资源
最近更新 更多