在python中使用PIL裁剪图像

Taj*_*yal 120 python crop python-imaging-library

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

nin*_*cko 178

有一种crop()方法:

w, h = yourImage.size
yourImage.crop((0, 30, w, h-30)).save(...)
Run Code Online (Sandbox Code Playgroud)

  • 对于像我这样懒惰的人来说,参数:box-裁剪矩形,作为(左,上,右,下)元组。 (5认同)
  • @TajKoyal:ninjagecko正在向你展示的是你如何从顶部和底部裁剪.他正在为新图像指定一个矩形.您可以看到他从顶部和底部点的y值上削减了30个像素.如果以任何方式偏移x值,那么会影响左侧和右侧. (3认同)
  • 是的,我知道 im.crop(box) 用于裁剪图像。但是我只想裁剪图像的上下部分而不是左右,虽然 box() 需要 4 元组,但我不知道如何裁剪图像的上下部分。 (2认同)

Atu*_*van 43

您需要为此导入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()
Run Code Online (Sandbox Code Playgroud)


Pou*_*yaB 12

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

from PIL import ImageOps

border = (0, 30, 0, 30) # left, up, right, bottom
ImageOps.crop(img, border)
Run Code Online (Sandbox Code Playgroud)


l m*_*zhi 5

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

  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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

坐标系

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

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