from PIL import Image
import numpy as np
def remove_alpha(img_path):
# Open image and ensure not palettised, make into Numpy array and select alpha channel
im = Image.open(img_path).convert('RGBA')
na = np.array(im)
alpha = na[:, :, 3]
# Find non-empty rows and columns
non_empty_rows = np.where(alpha.max(axis=1) > 0)[0]
non_empty_columns = np.where(alpha.max(axis=0) > 0)[0]
# Copy them to new image
opaque = na[non_empty_rows, :, :][:, non_empty_columns, :]
# Create new image with non-empty rows and columns
new_image = Image.fromarray(opaque)
# Save the new image
new_image.save(f'{tmp_img_name}.png')
remove_alpha(r'C:\Users\Administrator\Desktop\c.png')
网友评论