Winston's answer is good, but for completeness, when you need to manipulate pixel by pixel in Python, you should avoid looping through each pixel, regardless of which image library is used. This processor intensity is due to the nature of the language and can rarely be used for real-time operation.
Fortunately, the excellent NumPy library can help you perform several scalar operations in byte streams, looping around each number in its own code, which is orders of magnitude higher than in Python. For this specific operation, if we use the xor operation with (2^32 - 1) , we can delegate the operation to the inner loop in native code.
This example, which you can paste directly into the Python console, instantly flips pixels to white (if you have NumPy installed):
import pygame srf = pygame.display.set_mode((640,480)) pixels = pygame.surfarray.pixels2d(srf) pixels ^= 2 ** 32 - 1 del pixels pygame.display.flip()
Without installing NumPy, the pygame.surfarray methods return regular Python arrays (from the stdlib array stdlib ), and you will have to look for another way to work with these numbers, since a regular Python array does not work with all elements when a string such as pixels ^= 2 ** 32 - 1 .
jsbueno
source share