Search code examples
pythonnumpypng

To delete a transparent area of an image in Python


I want to use Python to cut the transparent area of the image file.

Please look at the picture below.

image 1 (original image)

enter image description here

image 2 (result image)

enter image description here

The original image has alternating opaque and transparent areas. I want to transform the image consisting of 1-spaces-2-spaces-3-spaces-4 like the original image into 1-2-3-4.

I tried the following code but failed to get the desired output

typfrom PIL import Image
import numpy as np

def trim_transparency(image):
    # Convert image to np.array
    im = np.array(image)

    # Import alpha channels only
    alpha = im[:, :, 3]

    # Found a range of nonzero indexes on each axis
    non_empty_columns = np.where(alpha.max(axis=0)>0)[0]
    non_empty_rows = np.where(alpha.max(axis=1)>0)[0]

    # Found a range of nonzero indexes on each axis
    cropBox = (min(non_empty_rows), max(non_empty_rows), min(non_empty_columns), max(non_empty_columns))

    image_data = Image.fromarray(im).crop(cropBox)

    return image_data

image = Image.open("original_image.png")
new_image = trim_transparency(image)
new_image.save("new_image.png")e here

Solution

  • You were very close - I would use Numpy indexing to gather the rows you want:

    from PIL import Image
    import numpy as np
    
    # Open image and ensure not palettised, make into Numpy array and select alpha channel
    im = Image.open('e0rRU.png').convert('RGBA')
    na = np.array(im)
    alpha = na[:, :, 3]
    
    # Find opaque rows
    non_empty_rows = np.where(alpha.max(axis=1)>0)[0]
    
    # Copy them to new image
    opaque = na[non_empty_rows,...]
    
    # Save
    Image.fromarray(opaque).save('result.png')
    

    enter image description here