Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invert colors of an image in pygame?

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()
like image 551
Ain Britain Avatar asked May 05 '11 01:05

Ain Britain


People also ask

How do I invert colors of an image in Python?

In this article, 2 methods have been described for inverting color space of an image. The first one is an inbuilt method using ImageChops. invert() function. In the second one we would be inverting the image by elementwise subtraction of pixel values.

How do you invert an image in Python?

Practical Data Science using Python To flip the image horizontally each row of the image will be reversed. And to invert the image each 0 will be replaced by 1, and each 1 will be replaced by 0. otherwise, Reverse[j]:= 1.

How do you reverse an image in pygame?

To flip the image we need to use pygame. transform. flip(Surface, xbool, ybool) method which is called to flip the image in vertical direction or horizontal direction according to our needs.


1 Answers

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.

like image 99
Winston Ewert Avatar answered Oct 10 '22 22:10

Winston Ewert