YOU*_*YOU 17
im.getbbox()=> 4元组或无
计算图像中非零区域的边界框.边界框作为定义左,上,右和下像素坐标的4元组返回.如果图像完全为空,则此方法返回None.
我尝试过的代码示例,我已经使用bmp进行了测试,但它也适用于png.
>>> import Image
>>> im=Image.open("test.bmp")
>>> im.size
(364, 471)
>>> im.getbbox()
(64, 89, 278, 267)
>>> im2=im.crop(im.getbbox())
>>> im2.size
(214, 178)
>>> im2.save("test2.bmp")
Run Code Online (Sandbox Code Playgroud)
这是现成的解决方案:
import numpy as np
from PIL import Image
def bbox(im):
a = np.array(im)[:,:,:3] # keep RGB only
m = np.any(a != [255, 255, 255], axis=2)
coords = np.argwhere(m)
y0, x0, y1, x1 = *np.min(coords, axis=0), *np.max(coords, axis=0)
return (x0, y0, x1+1, y1+1)
im = Image.open('test.png')
print(bbox(im)) # (33, 12, 223, 80)
im2 = im.crop(bbox(im))
im2.save('test_cropped.png')
Run Code Online (Sandbox Code Playgroud)
输入示例(如果您想尝试,请下载链接):
输出:
我今天也遇到了同样的问题。这是我裁剪透明边框的解决方案。只需将此脚本与批处理 .png 文件一起放入您的文件夹中即可:
from PIL import Image
import numpy as np
from os import listdir
def crop(png_image_name):
pil_image = Image.open(png_image_name)
np_array = np.array(pil_image)
blank_px = [255, 255, 255, 0]
mask = np_array != blank_px
coords = np.argwhere(mask)
x0, y0, z0 = coords.min(axis=0)
x1, y1, z1 = coords.max(axis=0) + 1
cropped_box = np_array[x0:x1, y0:y1, z0:z1]
pil_image = Image.fromarray(cropped_box, 'RGBA')
print(pil_image.width, pil_image.height)
pil_image.save(png_image_name)
print(png_image_name)
for f in listdir('.'):
if f.endswith('.png'):
crop(f)
Run Code Online (Sandbox Code Playgroud)