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()
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With