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
Trouble is getbbox()
crops off the black borders, from the docs: 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
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)