0

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

Onur-Andros Ozbek
  • 2,998
  • 2
  • 29
  • 78

1 Answers1

1

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")
Halmon
  • 1,027
  • 7
  • 13
  • When I try to paste the cropped logo (from your code) on the canvas, I get this error: `text_img.paste(new_logo, (logo_position_x, logo_position_y), mask=new_logo)` – Onur-Andros Ozbek Dec 31 '20 at 21:44
  • @oo92 Do you have the error that came with your paste code? – Halmon Jan 01 '21 at 00:58
  • Yea and I diagnosed it. Turns out some of the images are of mode `LA`. I tried to convert them to `logo.convert(mode='RGBA')` but it didn't work – Onur-Andros Ozbek Jan 01 '21 at 01:01