python图像库(PIL)中的getbbox方法不起作用

时间:2012-03-26 10:58:37

标签: python python-imaging-library crop bounding-box image-editing

我想通过剪切边框上的白色区域将图像裁剪为较小的尺寸。我尝试了在这个论坛Crop a PNG image to its minimum size中建议的解决方案,但是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版本的图,没有运气 任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:19)

问题是getbbox()从文档:Calculates the bounding box of the non-zero regions in the image中删除黑色边框。

enter image description here enter image description here

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)
相关问题