getbbox method from python image library (PIL) not working

不想你离开。 提交于 2020-03-17 07:23:07

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/9870876/getbbox-method-from-python-image-library-pil-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!