简体   繁体   English

如何使用 PIL 裁剪图像?

[英]How to crop an image using PIL?

I want to crop image in the way by removing first 30 rows and last 30 rows from the given image.我想通过从给定图像中删除前 30 行和后 30 行来裁剪图像。 I have searched but did not get the exact solution.我已经搜索过,但没有得到确切的解决方案。 Does somebody have some suggestions?有人有什么建议吗?

There is a crop() method:有一个crop()方法:

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

You need to import PIL (Pillow) for this.为此,您需要导入 PIL(枕头)。 Suppose you have an image of size 1200, 1600. We will crop image from 400, 400 to 800, 800假设您有一张大小为 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()

(left, upper, right, lower) means two points, (左,上,右,下)表示两点,

  1. (left, upper) (左,上)
  2. (right, lower) (右下)

with an 800x600 pixel image, the image's left upper point is (0, 0), the right lower point is (800, 600).对于 800x600 像素的图像,图像的左上点是 (0, 0),右下点是 (800, 600)。

So, for cutting the image half:因此,为了将图像切成两半:

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()

在此处输入图片说明

Coordinate System 坐标系

The Python Imaging Library uses a Cartesian pixel coordinate system, with (0,0) in the upper left corner. Python 成像库使用笛卡尔像素坐标系,左上角为 (0,0)。 Note that the coordinates refer to the implied pixel corners;请注意,坐标是指隐含的像素角; the centre of a pixel addressed as (0, 0) actually lies at (0.5, 0.5).寻址为 (0, 0) 的像素的中心实际上位于 (0.5, 0.5)。

Coordinates are usually passed to the library as 2-tuples (x, y).坐标通常作为 2 元组 (x, y) 传递给库。 Rectangles are represented as 4-tuples, with the upper left corner given first.矩形表示为 4 元组,首先给出左上角。 For example, a rectangle covering all of an 800x600 pixel image is written as (0, 0, 800, 600).例如,一个覆盖所有 800x600 像素图像的矩形被写为 (0, 0, 800, 600)。

An easier way to do this is using crop from ImageOps .一种更简单的方法是使用ImageOps 中的裁剪 You can feed the number of pixels you want to crop from each side.您可以输入要从每一侧裁剪的像素数。

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