如何在pygame中反转图像的颜色?

Ain*_*ain 8 python graphics pygame colors inversion

我有一个pygame Surface,想要反转颜色.有没有比这更快更pythonic的方法?这很慢.

我知道从255中减去这个值不是"倒置颜色"的唯一定义,但它是我现在想要的.

我很惊讶pygame没有这样内置的东西!

谢谢你的帮助!

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()
Run Code Online (Sandbox Code Playgroud)

Win*_*ert 8

摘自: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
Run Code Online (Sandbox Code Playgroud)

这可能会导致alpha通道错误,但您应该可以通过其他调整来实现.


jsb*_*eno 6

Winston的答案很好,但是为了完整起见,当必须在Python中逐个像素地操作图像时,无论使用哪个图像库,都应该避免遍历每个像素.由于语言的性质,这是CPU密集型的,很少能够实时工作.

幸运的是,优秀的NumPy库可以帮助在字节流中执行多个标量操作,循环遍历本机代码中的每个数字,这比仅在Python中执行它快几个数量级.对于此特定操作,如果我们使用xor操作(2^32 - 1),我们可以将操作委托给本机代码中的内部循环.

这个例子,您可以直接粘贴到您的Python控制台,将像素立即翻转为白色(如果您安装了NumPy):

import pygame

srf = pygame.display.set_mode((640,480))
pixels = pygame.surfarray.pixels2d(srf)
pixels ^= 2 ** 32 - 1
del pixels

pygame.display.flip()
Run Code Online (Sandbox Code Playgroud)

如果没有安装NumPy,pygame.surfarray方法将返回普通的Python数组(来自stdlib数组模块),你必须找到另外一种操作这些数字的方法,因为普通的Python数组在pixels ^= 2 ** 32 - 1给出这样的行时不会对所有元素进行操作.