8

我想通过切割边框上的白色区域来将图像裁剪为更小的尺寸。我尝试了这个论坛中建议的解决方案将 PNG 图像裁剪到最小尺寸,但是 pil 的 getbbox() 方法返回了一个与图像大小相同的边界框,即它似乎无法识别空白区域大约。我尝试了以下方法:

>>>import Image
>>>im=Image.open("myfile.png")
>>>print im.format, im.size, im.mode
>>>print im.getbbox()
PNG (2400,1800) RGBA
(0,0,2400,1800)

通过使用 GIMP 自动裁剪来裁剪图像,我检查了我的图像是否具有真正的白色可裁剪边框。我还尝试了该图的 ps 和 eps 版本,但没有运气。
任何帮助将不胜感激。

4

1 回答 1

21

麻烦是getbbox()从文档中裁剪掉黑色边框:Calculates the bounding box of the non-zero regions in the image.

在此处输入图像描述在此处输入图像描述

import Image    
im=Image.open("flowers_white_border.jpg")
print im.format, im.size, im.mode
print im.getbbox()
# white border output:
JPEG (300, 225) RGB
(0, 0, 300, 225)

im=Image.open("flowers_black_border.jpg")
print im.format, im.size, im.mode
print im.getbbox()
# black border output:
JPEG (300, 225) RGB
(16, 16, 288, 216) # cropped as desired

我们可以对白色边框进行简单的修复,首先使用 反转图像ImageOps.invert,然后使用getbbox()

import ImageOps
im=Image.open("flowers_white_border.jpg")
invert_im = ImageOps.invert(im)
print invert_im.getbbox()
# output:
(16, 16, 288, 216)
于 2012-03-26T14:46:10.637 回答