我编写的代码应该允许我浏览每列的y值并返回每个像素的RBG值。我试图在我的图像中找到所有纯白色像素。但是出于某种原因,我发现错误:“IndexError:图像索引超出范围”,当找到第一列中的最终值时。我怎样才能进入下一栏?
我的代码如下所示:
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)
答案 0 :(得分:0)
您只需将'&lt; ='更改为'&lt;'在两个while循环中。
主要原因是索引从0开始。所以如果你看图像大小它会是(100,100),但如果你试图访问像素像素[100,100]它就不存在了。
但pix [99,99]存在且对应于pix [100,100]。
干杯,
答案 1 :(得分:0)
使用零索引,最后一个索引比大小小一个。因此,您需要将<=
更改为<
。此外,此问题应该有index
标记。
有几种方法可以使用内置函数来执行此任务。请参阅此问题以获取示例。 How to count the occurrence of certain item in an ndarray in Python?。这些解决方案很可能会快得多。
答案 2 :(得分:0)
而不是while
循环尝试以下代码:
[width, height] = newimage2.size
for x in range(width):
for y in range(height):
cpixel = pixels[x, y]
if(cpixel ==(255,255,255):
whitevalues = whitevalues + 1
这将确保索引在范围内。
答案 3 :(得分:0)
Python是zero-indexed
,即如果您有list
,例如:
l = [1, 4, 7, 3, 6]
并且您希望iterate
通过while loop
(for-loop
会更好,但没关系),那么您必须loop
< em> while
index
小于length
的list
- 因此index
实际上不是length
{1}}的{1}},之前只有list
。
上面1
上iterating
的代码如下所示:
list
将为您提供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)
对于这个应用程序会更好,因为它需要更少的行并且更像Pythonic。所以这里是for-loop
的代码,您可能会发现它很有用:
for-loop
或者,如果你想成为非常pythonic,你可以在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)
中执行此操作:
list-comprehension
答案 4 :(得分:0)
其他答案解释了为什么你的代码不起作用,所以这只是为了展示另一种计算白色像素的方法:
from PIL import Image
image_path = '/path/to/image'
image = Image.open(image_path)
count = 0
# image.getdata() returns all the pixels in the image
for pixel in image.getdata():
if pixel == (255, 255, 255):
count += 1
print(count)