我已经编写了允许我遍历每一列的y值并返回每个像素的RBG值的代码。我正在尝试找到我的图像中所有的纯白色像素。但是,由于某些原因,当找到第一列中的最后一个值时,我会看到错误:"IndexError: image index out of range“。我如何才能继续下一列?
我的代码如下所示:
from PIL import Image
pix = newimage2.load()
print(newimage2.size)
print(" ")
whitevalues = 0
x = 0
while x <= newimage2.width:
y = 0
while y <= newimage2.height:
print(pix[x,y])
if pix[x,y] == (255,255,255):
whitevalues = whitevalues + 1
y = y+1
x = x+1
print(whitevalues)发布于 2017-10-28 01:05:26
Python是zero-indexed,也就是说,如果你有一个list,比如:
l = [1, 4, 7, 3, 6]如果你想用代码通过它( for-loop会更好,但不要紧),那么你就必须比< loop >E221iterate > while loop的while index is loop-所以<代码>D25实际上从来不是<代码>D27的<代码>D26,直到之前的<代码>D28。
上面的list上的iterating代码看起来像这样:
i = 0
while i < len(l):
print(l[i])
i += 1这将为您提供以下output:
1
4
7
3
6同样的逻辑也适用于您的image --毕竟它本质上只是一个2-dimensional list。
这意味着您需要将代码中的less than or equal (<=)比较器更正为less thans (<)。那么你的代码应该按照你想要的方式工作。
所以这将是修正后的代码:
from PIL import Image
pix = newimage2.load()
print(newimage2.size)
print(" ")
whitevalues = 0
x = 0
while x < newimage2.width:
y = 0
while y < newimage2.height:
print(pix[x,y])
if pix[x,y] == (255,255,255):
whitevalues += 1
y += 1
x += 1
print(whitevalues)但是,正如我在开始时提到的,for-loop更适合这个应用程序,因为它需要更少的代码行,并且更具Pythonic风格。下面是你可能会发现有用的for-loop代码:
from PIL import Image
pix = newimage2.load()
print(newimage2.size)
print(" ")
whitevalues = 0
for row in newimage2
for col in row:
print(col)
if col == (255,255,255):
whitevalues += 1
print(whitevalues)或者,如果您想使用pythonic语言,可以在list-comprehension中完成此操作
whitevalues = sum([1 for r in pix for c in r if c == 1])发布于 2017-10-28 00:57:05
您只需在两者的while循环中将'<=‘更改为'<’即可。
主要原因是索引从0开始。因此,如果你查看图像大小,它将是(100,100),但如果你试图访问像素100,100,它就不存在。
但是像素99,99是存在的,并且对应于像素100,100。
干杯,
发布于 2017-10-28 00:57:54
使用零索引时,最后一个索引比大小小一。因此,您需要将<=更改为<。另外,这个问题应该有一个index标签。
有几种方法可以使用内置函数来执行此任务。有关示例,请参阅此问题。How to count the occurrence of certain item in an ndarray in Python?。这些解决方案很可能会更快。
https://stackoverflow.com/questions/46979774
复制相似问题