Search code examples
pythonpygamesurface

How to whitelist certain colours in a pygame surface


is there a way to whitelist colours on a surface in pygame and any colour that is not in that whitelist becomes transparent?

ive tried to use icon.set_colorkey() but that only removes one colour


Solution

  • You have to do it manually Ensure that format of the image has an alpha channel by pygame.Surface.convert_alpha(). Identify all the pixel, which have a red green and blue color channel above a certain threshold (e.g. 230). Change the color channels and the alpha channel of those pixels to (0, 0, 0, 0):

    img = pygame.image.load(IMAGE).convert_alpha()
    
    threshold = 230
    for x in range(img.get_width()):
        for y in range(img.get_height()):
            color = img.get_at((x, y))
            if color.r > threshold and color.g > threshold and color.b > threshold:
                img.set_at((x, y), (0, 0, 0, 0))