Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get grayscale value with PIL?

Tags:

python

I did a code to print all of the images pixel's grayscale values

Here is my code:

from PIL import Image, ImageColor
im = Image.open('upvote.png')
im = im.resize((50, 50))
im = im.convert('LA')#convert to grayscale
for i in range(50):
    print('\n')
    for j in range(50):
        pixel = im[i, j]# get pixel value
        print(pixel)

It is expected to get something like this:
1 1 1 1 1 1 3 3 3 3 3 1 1 1 1 1
3 3 3 3 3 3 1 1 1 1 1 3 3 3 3 3
1 1 1 1 1 1 3 3 3 3 3 3 3 3 3 3
....
depending on the image

but I am getting this error:

TypeError: 'Image' object is not subscriptable
like image 417
rafa_rrayes Avatar asked Nov 24 '25 04:11

rafa_rrayes


1 Answers

Alright, if anyone ever sees this here is how I solved it:
Instead of this:

pixel = im[i, j]

I used this:

pixel = im.getpixel((i, j))
like image 95
rafa_rrayes Avatar answered Nov 26 '25 20:11

rafa_rrayes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!