繁体   English   中英

如何使用 PIL 裁剪图像?

[英]How to crop an image using PIL?

我想通过从给定图像中删除前 30 行和后 30 行来裁剪图像。 我已经搜索过,但没有得到确切的解决方案。 有人有什么建议吗?

有一个crop()方法:

w, h = yourImage.size
yourImage.crop((0, 30, w, h-30)).save(...)

为此,您需要导入 PIL(枕头)。 假设您有一张大小为 1200, 1600 的图像。我们将把图像从 400, 400 裁剪为 800, 800

from PIL import Image
img = Image.open("ImageName.jpg")
area = (400, 400, 800, 800)
cropped_img = img.crop(area)
cropped_img.show()

(左,上,右,下)表示两点,

  1. (左,上)
  2. (右下)

对于 800x600 像素的图像,图像的左上点是 (0, 0),右下点是 (800, 600)。

因此,为了将图像切成两半:

from PIL import Image
img = Image.open("ImageName.jpg")

img_left_area = (0, 0, 400, 600)
img_right_area = (400, 0, 800, 600)

img_left = img.crop(img_left_area)
img_right = img.crop(img_right_area)

img_left.show()
img_right.show()

在此处输入图片说明

坐标系

Python 成像库使用笛卡尔像素坐标系,左上角为 (0,0)。 请注意,坐标是指隐含的像素角; 寻址为 (0, 0) 的像素的中心实际上位于 (0.5, 0.5)。

坐标通常作为 2 元组 (x, y) 传递给库。 矩形表示为 4 元组,首先给出左上角。 例如,一个覆盖所有 800x600 像素图像的矩形被写为 (0, 0, 800, 600)。

一种更简单的方法是使用ImageOps 中的裁剪 您可以输入要从每一侧裁剪的像素数。

from PIL import ImageOps

border = (0, 30, 0, 30) # left, top, right, bottom
ImageOps.crop(img, border)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM