Python:我的while循环一直在添加列表中的第一种颜色

Python:我的while循环一直在添加列表中的第一种颜色,python,loops,while-loop,euclidean-distance,ppm,Python,Loops,While Loop,Euclidean Distance,Ppm,我的while循环没有正确执行。它将通过并以它应该的方式递增i,但它不会在循环外递增i。这意味着它会不断追加相同的rgb像素颜色对约4000次。有什么想法吗 输入文件示例:(我跳过前三行,因为这是文件类型、照片尺寸或颜色。其余是r、g、b像素数据。每三行是r、g、b顺序的一个像素) 我的代码: import math with open('Ocean.ppm','r') as f: output = f.read().split("\n") i = 0 r_point = 3 + i

我的while循环没有正确执行。它将通过并以它应该的方式递增i,但它不会在循环外递增i。这意味着它会不断追加相同的rgb像素颜色对约4000次。有什么想法吗

输入文件示例:(我跳过前三行,因为这是文件类型、照片尺寸或颜色。其余是r、g、b像素数据。每三行是r、g、b顺序的一个像素)

我的代码:

import math

with open('Ocean.ppm','r') as f:
    output = f.read().split("\n")
i = 0
r_point = 3 + i
g_point = 4 + i
b_point = 5 + i

resolution = []
resolution.append(output[1].split(" "))
file_size = resolution[0]
file_size = int(file_size[0]) * int(file_size[1])
file_size = int(file_size*3)
print(file_size)

pixel_list = []
pixel_list.append(str(output[0]))
pixel_list.append(str(output[1]))
pixel_list.append(str(output[2]))

while file_size >= i:
    red   = math.sqrt((int(output[r_point])-255)**2 + (int(output[g_point]) - 0)**2 + (int(output[b_point])-0)**2)
    green = math.sqrt((int(output[r_point])-0)**2 + (int(output[g_point]) - 255)**2 + (int(output[b_point])-0)**2)
    blue  = math.sqrt((int(output[r_point])-0)**2 + (int(output[g_point]) - 0)**2 + (int(output[b_point])-255)**2)
    white = math.sqrt((int(output[r_point])-0)**2 + (int(output[g_point]) - 0)**2 + (int(output[b_point])-0)**2)
    black = math.sqrt((int(output[r_point])-255)**2 + (int(output[g_point]) - 255)**2 + (int(output[b_point])-255)**2)

    L = [red, green, blue, white, black]
    idx = min(range(len(L)), key=L.__getitem__)

    if idx == 0:
        # red
        pixel_list.append('255')
        pixel_list.append('0')
        pixel_list.append('0')
        i += 3

    elif idx == 1:
        # green
        pixel_list.append('0')
        pixel_list.append('255')
        pixel_list.append('0')
        i += 3


    elif idx == 2:
        # blue
        pixel_list.append('0')
        pixel_list.append('0')
        pixel_list.append('255')
        i += 3


    elif idx == 3:
        # white
        pixel_list.append('0')
        pixel_list.append('0')
        pixel_list.append('0')
        i += 3


    elif idx == 4:
        # black
        pixel_list.append('255')
        pixel_list.append('255')
        pixel_list.append('255')
        i += 3



f = open('myfile.ppm','w')
for line in pixel_list:
    f.write(line + "\n")

我认为您只需要将以下内容移动到循环内部:

r_point = 3 + i
g_point = 4 + i
b_point = 5 + i

这样,它将更新列表的索引。

我还没有测试任何东西。但可能会将递增i放在if语句的末尾,而不是每个if语句中。另外,请尝试打印idx值,看看它是否介于0和4之间。代码中有一些特殊的语句。。理解它的作用和原因是相当复杂的。没有给出输入文件格式
r_point = 3 + i
g_point = 4 + i
b_point = 5 + i