【问题标题】:getbbox method from python image library (PIL) not workingpython图像库(PIL)中的getbbox方法不起作用
【发布时间】:2012-04-09 21:11:15
【问题描述】:

我想通过剪切边框上的白色区域将图像裁剪为更小的尺寸。我尝试了这个论坛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 版本的图,但没有运气。
任何帮助将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    问题是 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)
    

    【讨论】:

    • 非常感谢您快速清晰的回复。它有效,但我必须先从 RGBA 转换为 RGB,然后才能使用 invert,方法是调用函数 convert: invert_im=im.convert("RGB") 然后 invert_im=ImageOps.invert(invert_im),否则我得到一个 IOError"此图像模式不支持”。
    • @user1292774 - 很酷,很高兴它成功了..,如果你愿意,你可以投票/并勾选左上角的箭头以接受答案,然后我们都会得到一些分数;)
    • 我已经尝试过投票,但我的积分不足 15 分,系统暂时不允许我,如果我得到这 15 分,我会这样做。谢谢!
    • @etepoc - 没有问题 :) 当我开始使用 SO、奖牌和所有东西时,这一切都让我感到困惑......
    猜你喜欢
    • 2016-10-22
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多