Python图像库(PIL)中的getbbox方法无法工作

2024-04-29 18:49:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把图像裁剪成更小的尺寸,把边界上的白色区域剪掉。我尝试了在这个论坛Crop a PNG image to its minimum size中建议的解决方案,但是pIL的GETBBOX()方法返回了相同大小的图像的边界框,也就是说,它似乎不识别周围的空白区域。我尝试了以下方法:

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

我检查了我的图像有真正的白色可裁剪的边界通过裁剪图像与GIMP自动裁剪。我还尝试了ps和eps版本的图形,但运气不佳。
任何帮助都将不胜感激。


Tags: to方法图像cropimage区域sizepng
1条回答
网友
1楼 · 发布于 2024-04-29 18:49:06

问题是getbbox()从文档中裁剪掉黑色边框: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

我们可以简单地修复白色边框,方法是首先使用ImageOps.invert反转图像,然后使用getbbox()

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

相关问题 更多 >