如何逐像素分析python中的图像

如何逐像素分析python中的图像,python,python-imaging-library,Python,Python Imaging Library,我已经编写了代码,可以让我遍历每列的y值,并返回每个像素的RBG值。我试图找到我的图像中所有的纯白色像素。然而,由于某种原因,当找到第一列中的最终值时,我会遇到错误:“IndexError:图像索引超出范围”。我怎样才能进入下一个专栏 我的代码如下所示: from PIL import Image pix = newimage2.load() print(newimage2.size) print(" ") whitevalues = 0 x = 0 while x <= newima

我已经编写了代码,可以让我遍历每列的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)
从PIL导入图像
pix=newimage2.load()
打印(新图像2.尺寸)
打印(“”)
白色值=0
x=0

虽然x只需使用零索引更改“,但最后一个索引比大小小一个。因此,您需要更改
而不是
,同时尝试以下代码:

[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

这将确保索引在范围内。

Python是
零索引的
,即如果您有
列表
,例如:

l = [1, 4, 7, 3, 6]
你想用一个
while loop
(一个
for loop
会更好,但没关系),然后你必须
循环
,而
索引
小于
列表的
长度
-因此
索引从来都不是
列表的
长度
,只是在
1
之前

在上面的
列表上迭代
的代码如下所示:

i = 0
while i < len(l):
   print(l[i])
   i += 1

同样的逻辑也适用于你的
图像
——毕竟它本质上只是一个
二维
列表


这意味着您需要更正
小于或等于
其他答案会解释代码不起作用的原因,因此这只是为了展示计算白色像素的另一种方法:

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)
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)
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)
whitevalues = sum([1 for r in pix for c in r if c == 1])
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)