简体   繁体   中英

How to solve: IndexError: image index out of range

I'm newbee in python and trying to get every 80th pixel in 80th row, here is my code:

from PIL import Image


im = Image.open("UIC.bmp")
size = (list(im.size))  #  size is 1200x800
pixel_row = []
for y in range(0,1200, 80):
    print(y)

    for x in range(0, 800, 80):
        print(x)
        cordinate = x, y
        pixel_row.append(im.getpixel(cordinate))


print(pixel_row)

After it's done, I decode text using the code:

print(pixel_list)

decode_list = []
for i in range(len(pixel_list)):
    decode_list.append(chr(pixel_list[i] - 100))

decode_text = ''.join(decode_list)

print(decode_text)

It gives an error:

Traceback (most recent call last):
  File "/Users/apple/Desktop/projects/BariySatarov/test.py", line 13, in <module>
    pixel_row.append(im.getpixel(cordinate)[2])
  File "/Users/apple/Desktop/projects/BariySatarov/venv/lib/python3.8/site-packages/PIL/Image.py", line 1358, in getpixel
    return self.im.getpixel(xy)
IndexError: image index out of range

Don't understand how to figure it out, because I get the same range as the range of the picture.

PS Tried to put range(0,1199, 80) and range(0, 799, 80), it doesn't work

You can use numpy and array indexing for this:

from PIL import Image
import numpy as np


im = Image.open("UIC.bmp")
arr = np.array(im)
pixel_row = arr[::80,::80].flatten()

You have to change between x and y.

x means column, not row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM