How to invert colors of an image in pygame?

Ain Britain picture Ain Britain · May 5, 2011 · Viewed 7k times · Source

I have a pygame Surface and would like to invert the colors. Is there any way quicker & more pythonic than this? It's rather slow.

I'm aware that subtracting the value from 255 isn't the only definition of an "inverted color," but it's what I want for now.

I'm surprised that pygame doesn't have something like this built in!

Thanks for your help!

import pygame

def invertImg(img):
    """Inverts the colors of a pygame Screen"""

    img.lock()

    for x in range(img.get_width()):
        for y in range(img.get_height()):
            RGBA = img.get_at((x,y))
            for i in range(3):
                # Invert RGB, but not Alpha
                RGBA[i] = 255 - RGBA[i]
            img.set_at((x,y),RGBA)

    img.unlock()

Answer

Winston Ewert picture Winston Ewert · May 5, 2011

Taken from: http://archives.seul.org/pygame/users/Sep-2008/msg00142.html

def inverted(img):
   inv = pygame.Surface(img.get_rect().size, pygame.SRCALPHA)
   inv.fill((255,255,255,255))
   inv.blit(img, (0,0), None, BLEND_RGB_SUB)
   return inv

This may do the alpha channel wrong, but you should be able to get that working with additional tweaks.