python映像库(PIL)中的getbbox方法不工作

python映像库(PIL)中的getbbox方法不工作,python,python-imaging-library,crop,bounding-box,image-editing,Python,Python Imaging Library,Crop,Bounding Box,Image Editing,我想把图像裁剪成更小的尺寸,在边框上剪下白色区域。我尝试了这个论坛中提出的解决方案,但是PIL的GETBBOX()方法返回了相同大小的图像的边界框,也就是说,它似乎不识别周围的空白区域。我尝试了以下方法: >>>import Image >>>im=Image.open("myfile.png") >>>print im.format, im.size, im.mode >>>print im.getbbox() 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版本的图形,但运气不佳。
非常感谢您的帮助。

麻烦在于
getbbox()
从文档中裁剪黑色边框:
计算图像中非零区域的边界框

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()
,轻松修复白色边框:


非常感谢您快速清晰的回复。这是可行的,但在使用invert之前,我必须先从RGBA转换为RGB,方法是调用函数convert:invert_im=im.convert(“RGB”),然后再调用invert_im=ImageOps.invert(invert_im),否则我会得到一个IOError“不支持此图像模式”。@user1292774-很酷,很高兴它能工作,如果您愿意,您可以向上投票/并勾选左上角的箭头以接受答案,然后我们都会得到一些分数;)我已经试着提高投票率,但我只有不到15分,而且系统暂时不允许我,如果我得到那15分,我会这样做。谢谢大家!@etepoc-没问题:)当我开始使用SO、奖牌和所有东西时,这一切都把我弄糊涂了。。
import ImageOps
im=Image.open("flowers_white_border.jpg")
invert_im = ImageOps.invert(im)
print invert_im.getbbox()
# output:
(16, 16, 288, 216)