简体   繁体   English

替换 Python 列表中的某些值

[英]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.但是,对于我正在运行的计算,我无法使用黑色像素表示的 0。 I have been trying to convert the 0s to 1s with the following code but it does not work despite producing no errors:我一直在尝试使用以下代码将 0 转换为 1,但尽管没有产生错误,但它不起作用:

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'"值得注意的是,当我尝试“item = 255”时,出现以下错误:“TypeError: '<' not supported between '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. data是一个列表列表,你需要嵌套循环。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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