getbbox method from python image library (PIL) not working
Asked Answered
G

1

9

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 getbbox() method of pil is returning a bounding box of the same size of the image, i.e., it seems that it doesn't recognize the blank areas around. I tried the following:

>>>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)

I checked that my image has truly white croppable borders by cropping the image with the GIMP auto-crop. I also tried with ps and eps versions of the figure, without luck.
Any help would be highly appreciated.

Gati answered 26/3, 2012 at 10:58 Comment(0)
P
25

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)
Peri answered 26/3, 2012 at 14:46 Comment(4)
Thank you a lot for the fast and clear response. It worked, but I had to convert first from RGBA to RGB before using invert, by calling the function convert: invert_im=im.convert("RGB") and then invert_im=ImageOps.invert(invert_im), otherwise I obtained an IOError "not supported for this image mode".Gati
@user1292774 - cool, glad it worked.. , if you like, you can upvote/ and tick the arrow to accept the answer, at the top left, then we both get some points ;)Peri
I already tried to upvote, but I have less than 15 points and the system doesn't let me for the moment, I will do if I ever get those 15 points. Thank you!Gati
@Gati - no probs :) it all confused the hell out of me when i started using SO, medals and everything..Peri

© 2022 - 2024 — McMap. All rights reserved.