Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pygame: Converting all white pixels to fully transparent in png image

I have been trying to create an image processing program to take all the white pixels (255,255,255) in a loaded image and set their alpha channels to 0 (non-opaque), and then save the image.

I've been using Python's pygame extension to help me achieve this, but so far I cannot find a simple way to do what I just described above.

Keep in mind I'm not trying to display an image, I'm trying to manipulate it.

like image 803
Sigma Freud Avatar asked Nov 04 '22 07:11

Sigma Freud


1 Answers

I also suggest using PIL or ImageMagick, but here is a way to do it in pygame:

import pygame

def convert():    
    pygame.init()
    pygame.display.set_mode()
    image = pygame.image.load("triangle.png").convert_alpha()
    for x in range(image.get_width()):
        for y in range(image.get_height()):
            if image.get_at((x, y)) == (255, 255, 255, 255):
                image.set_at((x, y), (255, 255, 255, 0))
    pygame.image.save(image, "converted.png")

if __name__ == "__main__":
    convert()

The above works for a white background. Here's how triangle.png and converted.png look using magenta instead of white so you can see the difference:

magenta bgtransparent bg

With the ImageMagick utility instead, it's as easy as running this on the command line:

convert original.png -transparent white converted.png
like image 127
0eggxactly Avatar answered Nov 12 '22 16:11

0eggxactly