首页 > 解决方案 > 在while循环中完成while循环后脚本冻结(oops)

问题描述

所以我试图获取图像中每个像素的 rgb 值,在它获取第一行的所有值之后,有什么想法吗?

脚本:

image = input("image:")
im = Image.open(image)
pix = im.load()
width, height = im.size
x = 0
y = 0
#for each pixel in the Y
while (y < height):
    # for each pixel in the X
 while (x < width):
     print pix[x,y]
     x = x + 1
y = y + 1

标签: pythonpython-3.ximagepython-2.7image-processing

解决方案


初始化 x 和 y 值的方式是问题所在。X 应在第二个 while 循环之前立即初始化回零,以便为下一行的宽度重新开始计数。就像是:

x = 0
y = 0
#for each pixel in the Y
while (y < height):
    # for each pixel in the X
 x = 0 #start counting again for the next row
 while (x < width):
     print pix[x,y]
     x = x + 1
y = y + 1

您的循环冻结,因为在第一行的末尾, x=width 并且您忘记将其重置为零以进行第一个 while 循环的第二次迭代。


推荐阅读