本文介绍了python图像库(PIL)中的getbbox方法不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过剪切边框上的白色区域将图像裁剪为较小的尺寸.我尝试了该论坛中建议的解决方案将PNG图片裁剪为最小尺寸,但是pil的getbbox()方法返回的是图像大小相同的边界框,即似乎无法识别周围的空白区域.我尝试了以下方法:

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)

我使用GIMP自动裁剪功能对图像进行了裁剪,以检查图像是否具有真正的白色可裁剪边框.我也尝试过该图的ps和eps版本,但没有运气.
任何帮助将不胜感激.

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.

推荐答案

问题是getbbox()从文档Calculates the bounding box of the non-zero regions in the image切掉了黑色边框.

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

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

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)

这篇关于python图像库(PIL)中的getbbox方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 06:13