Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getbbox method from python image library (PIL) not working

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.

like image 948
etepoc Avatar asked Mar 26 '12 10:03

etepoc


People also ask

How do I import an image into Python using PIL?

To load the image, we simply import the image module from the pillow and call the Image. open(), passing the image filename. Instead of calling the Pillow module, we will call the PIL module as to make it backward compatible with an older module called Python Imaging Library (PIL).

What is getBBox in Python?

getBBox() method allows us to determine the coordinates of the smallest rectangle in which the object fits.


1 Answers

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)
like image 53
fraxel Avatar answered Oct 03 '22 05:10

fraxel