mchd
mchd

Reputation: 3163

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

Upvotes: 1

Views: 1891

Answers (1)

Halmon
Halmon

Reputation: 1077

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

Upvotes: 2

Related Questions