Question:
I’m looking for a faster way to read each screen pixel in an image. I need to scan each frame in a 640px×360px video, and get back its colour, so I can run an if else statement on which item is added to a list. I have 3 test images that are very small and are read quickly, but it takes a very long time to read the doom logo picture.
The test image sizes are 2px×2px, and 8px×8px. The doom image is 512px×512px.
In the pixel_rgb function, you create an instance of the Image class, which takes a lot of time. And if the pixel_rgb function is called 262144 (image 512px×512px), then the function will create a new instance of the Image class 262144 times. Because of this, the code will run slowly. But instead of constantly creating a new instance of the Image class, you can create it once, and work with it in the pixel_rgb function (as an argument, the function should take not the path to the image, but the image itself).
Here is the corrected code (I removed the unnecessary use of the pixel_y variable and replaced int("0") to 0):
from PIL import Image
def pixel_rgb(img, x, y):
r, g, b = img.getpixel((x, y))
a = (r, g, b)
print(a)
def check_frame(item):
pixel_x = 0
pixel_y = 0
for i in range(8):
for i in range(8):
pixel_rgb(item, pixel_x, pixel_y)
pixel_x += 1
pixel_x = 0
pixel_y += 1
img = Image.open("test-3.png").convert('RGB')
check_frame(img)