【问题标题】:Python: My while loop keeps appending the first color in the listPython:我的 while 循环不断在列表中附加第一个颜色
【发布时间】:2015-11-16 03:08:31
【问题描述】:

我的 while 循环没有正确执行。它将按照预期的方式遍历并增加 i ,但不会在循环之外增加 i 。这意味着它会不断添加相同的 rgb 像素颜色对 ~4000 次。有什么想法吗?

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

P3
200 200
255
192
48
64
216
52
180
252
8
176
212
96
4
152
108
108
20
248
64
80
140
132

我的代码:

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")

【问题讨论】:

  • 我没有测试任何东西。但也许在最后的 if 语句之外而不是在每个 if 中增加 i。还可以尝试打印您的 idx 值,看看它是否在 0 到 4 之间
  • 代码中有一些特殊的语句。 ..理解它的作用和原因相当复杂。没有给出输入文件格式

标签: python loops while-loop euclidean-distance ppm


【解决方案1】:

我认为您只需将以下内容移至 inside 循环:

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

这样,它会将索引更新到您的列表中。

【讨论】:

    猜你喜欢
    • 2021-04-06
    • 1970-01-01
    • 2014-03-22
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多