get pixel color python code example

Example 1: python get pixel values from image

from PIL import Image

img = Image.open('example.png')
imgWidth, imgHeight = img.size
img = img.convert("RGBA")
imgdata = img.getdata()

x_pos = 0
y_pos = 1

pixel_value = []
x = []
y = []

for item in imgdata:
    if (x_pos) == imgWidth:
        x_pos = 1
        y_pos += 1
    else:
        x_pos += 1

    if item[3] != 0:
        pixel_value.append(item[2])
        x.append(x_pos)
        y.append(y_pos)

pixel_value, x, y = zip(*sorted(zip(pixel_value, x, y), reverse=True))

print(f'{pixel_value}\n{x}\n{y}')

Example 2: python get pixel color from screen

I had this same exact problem, and solved it (in Java, in C#). The main idea behind the solution is GetPixel from screen is slow, and you can't fix that. But as you need some pixels, you can get a bunch of them all at once.

The time that it took to get 64 pixels was 98 times faster.

Example 3: how to get RGB value from pixel in screen live python

import PIL.ImageGrab
rgb = PIL.ImageGrab.grab().load()[x,y]