get image pixel 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 pil get pixel
im = Image.open('image.gif')
rgb_im = im.convert('RGB')
r, g, b = rgb_im.getpixel((1, 1))
print(r, g, b)
>>> (65, 100, 137)