Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从中心裁剪具有特定尺寸的图像?_Python_Python Imaging Library_Crop - Fatal编程技术网

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

Python 如何从中心裁剪具有特定尺寸的图像?,python,python-imaging-library,crop,Python,Python Imaging Library,Crop,假设我们有一个具有以下尺寸的图像: 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) 至少有两种方法可以裁剪我能想到的图像

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

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)

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

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)
另一种方法是通过函数来实现,该函数在四个边上分别传递边界大小:

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像素宽度和高度的一半。它是½,因为长方体居中,所以大部分位于中点的两侧。