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

ete*_*poc 7 python crop bounding-box image-editing python-imaging-library

我想通过剪切边框上的白色区域将图像裁剪为较小的尺寸.我尝试了在这个论坛中建议的解决方案将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)
Run Code Online (Sandbox Code Playgroud)

我通过使用GIMP自动裁剪裁剪图像来检查我的图像是否具有真正的白色可裁剪边框.我也试过ps和eps版本的图,没有运气.
任何帮助将受到高度赞赏.

fra*_*xel 19

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

我们可以通过首先使用反转图像来轻松修复白色边框,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)
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢您快速而明确的回复.它工作,但我必须先使用RGBA转换为RGB才能使用反转,通过调用函数convert:invert_im = im.convert("RGB")然后反转_im = ImageOps.invert(invert_im),否则我获得了一个IOError"此图像模式不支持". (3认同)