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

oo92
  • 2,594
  • 2
  • 19
  • 49
  • Please share representative images, saying which ones are ok and which ones are problematic and also share your code. – Mark Setchell Dec 31 '20 at 21:08
  • @MarkSetchell The second one is ok, the first one isn't. What code specifically? At the moment, I don't have any code that removes extra transparency. – oo92 Dec 31 '20 at 21:10
  • If the image itself already has the extra alpha area, you can crop it using any image editor – Halmon Dec 31 '20 at 21:12
  • 1
    @Halmon Right but I want to do it using Python because I could add 100s of logos to this directory and I can't just manually crop all of them. I want to programmatically remove the extra transparency.. – oo92 Dec 31 '20 at 21:14
  • How can I trim your logos when you haven't shared your logos - other than merged with some background? – Mark Setchell Dec 31 '20 at 21:14
  • 1
    https://stackoverflow.com/a/63244423/2836621 – Mark Setchell Dec 31 '20 at 21:16
  • @MarkSetchell Check the edit. I added some of the logos.. – oo92 Dec 31 '20 at 21:20

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
  • 992
  • 6
  • 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)` – oo92 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 – oo92 Jan 01 '21 at 01:01