Python 是zero-indexed,即如果你有一个list,例如:
l = [1, 4, 7, 3, 6]
如果你想通过iterate 使用while loop(for-loop 会更好,但没关系),那么你将不得不loop while@987654329 @ 小于list 的length - 所以index 实际上从来不是list 的length,只是之前的1。 p>
iterating 上面 list 的代码如下所示:
i = 0
while i < len(l):
print(l[i])
i += 1
这会给你output:
1
4
7
3
6
同样的逻辑也适用于你的image——毕竟它本质上只是一个2-dimensionallist。
这意味着您需要将代码中的 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])