getbbox method from python image library (PIL) not working

前端 未结 1 1638
遇见更好的自我
遇见更好的自我 2021-02-06 06:25

I want to crop an image to its smaller size, by cutting the white areas on the borders. I tried the solution suggested in this forum Crop a PNG image to its minimum size but the

1条回答
  •  梦谈多话
    2021-02-06 07:23

    Trouble is getbbox() crops off the black borders, from the docs: Calculates the bounding box of the non-zero regions in the image.

    enter image description hereenter 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
    

    We can do an easy fix for white borders, by first inverting the image using ImageOps.invert, and then use getbbox():

    import ImageOps
    im=Image.open("flowers_white_border.jpg")
    invert_im = ImageOps.invert(im)
    print invert_im.getbbox()
    # output:
    (16, 16, 288, 216)
    

    0 讨论(0)
提交回复
热议问题