标签归档:crop

如何使用PIL裁剪图像?

问题:如何使用PIL裁剪图像?

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

I want to crop image in the way by removing first 30 rows and last 30 rows from the given image. I have searched but did not get the exact solution. Does somebody have some suggestions?


回答 0

有一种crop()方法:

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

There is a crop() method:

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

回答 1

您需要为此导入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()

You need to import PIL (Pillow) for this. Suppose you have an image of size 1200, 1600. We will crop image from 400, 400 to 800, 800

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

回答 2

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

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

对于800×600像素的图像,图像的左上点是(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 Imaging Library使用笛卡尔像素坐标系,左上角为(0,0)。注意,坐标指的是隐含的像素角。寻址为(0,0)的像素的中心实际上位于(0.5,0.5)。

坐标通常以2元组(x,y)的形式传递给库。矩形用4元组表示,左上角在前。例如,将覆盖所有800×600像素图像的矩形写为(0,0,800,600)。

(left, upper, right, lower) means two points,

  1. (left, upper)
  2. (right, lower)

with an 800×600 pixel image, the image’s left upper point is (0, 0), the right lower point is (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. 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).

Coordinates are usually passed to the library as 2-tuples (x, y). Rectangles are represented as 4-tuples, with the upper left corner given first. For example, a rectangle covering all of an 800×600 pixel image is written as (0, 0, 800, 600).


回答 3

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

from PIL import ImageOps

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

An easier way to do this is using crop from 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, up, right, bottom
ImageOps.crop(img, border)