Using pygame.surfarray
to handle an image as an array, manipulating any element in a array3d
is more than 5 times slower than manipulating a array2d
element. / p>
See this benchmark:
from datetime import *
import pygame
image = pygame.image.load('8000x8000.png')
arr = pygame.surfarray.array3d(image)
start = datetime.now()
for y in range(8000):
for x in range(8000):
if arr[x, y, 0] != 0:
pass
end = datetime.now()
print(end - start)
In the above case, an 8000 x 8000 image is read pixel by pixel.
array3d
returns the elements in this format: [R, G, B]. Ex: (255, 255, 255)
= White.
In the example above, processing elements 8000 ^ 2 using array3d takes the total time: 0:01:41.996732
Now, doing exactly the same, just changing to array2d
:
...
arr = pygame.surfarray.array2d(image)
...
if arr[x, y] != 0:
...
Total time is: 0:00:20.632741
, that is, more than 5 times faster .
Why this?