簡體   English   中英

Python:我的while循環不斷添加列表中的第一個顏色

[英]Python: My while loop keeps appending the first color in the list

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

我想你只需要下面移到循環

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

這樣,它將把索引更新到您的列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM