简体   繁体   中英

Replacing certain values in Python List

I have created a list for displaying a black/white (binary) image with its pixel values. However for the calculations I am running I can not work with 0s represented by the black pixels. I have been trying to convert the 0s to 1s with the following code but it does not work despite producing no errors:

from PIL import Image

img = Image.open('C:/Users/binary.png', 'r')  
WIDTH, HEIGHT = img.size

data = list(img.getdata())  # convert image data to a list of integers
data = [data[offset:offset + WIDTH] for offset in range(0, WIDTH * HEIGHT, WIDTH)]

for (i, item) in enumerate(data):
    if item == 0:
        data[i] = 1

for row in data:
    print(' '.join('{:3}'.format(value) for value in row))

It might be noteworthy that when I try "item = 255" I get the following error: "TypeError: '<' not supported between instances of 'list' and 'int'"

However this error doesn't make sense to me as when I do type(data) I get list output

data is a list of lists, you need nested loops.

for row in data:
    for i, value in enumerate(row):
        if value == 0:
            row[i] = 1

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