Crop a PNG image to its minimum size

前端 未结 6 853
旧巷少年郎
旧巷少年郎 2020-12-16 00:00

How to cut off the blank border area of a PNG image and shrink it to its minimum size using Python?

6条回答
  •  忘掉有多难
    2020-12-16 00:55

    Here is ready-to-use solution:

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

    Example input (download link if you want to try):

    Output:

提交回复
热议问题