Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

python - How to remove extra transparent pixels from an image

I have a series of transparent logos. I paste them on a canvas using PIL. Some of these logos have extra transparent pixels that make the bounding box too wide, like this:

enter image description here

However, I need these logos and the bounding boxes to be like this:

enter image description here

How can I remove these extra, unnecessary transparent pixels so the bounding box wraps the logo properly?

Here are some of the logos:

enter image description here enter image description here enter image description here enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From this answer, you can calculate the bounding box of the non-zero regions (transparent/alpha) and then programmatically crop it.

Snippet from answer:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...