2017-08-03 70 views
-1

我有一個包含座標和顏色代碼的.txt文件。我想從這個Python Pillow使用像素列表創建圖像

我的例子txt文件創建映像:

1,1#f8f3ed 
1,2#fff9f1 
1,3#faf2e7 
1,4#fbf2e1 
1,5#f6eed9 
1,6#e1d6c0 
1,7#e2d6be 
1,8#ebdfc5 
1,9#d0c4ac 
1,10#cdc2ac 
1,11#e3dbc6 
1,12#ded7c5 
. 
. 
187,249#1b2019 

如何創建這個形象?

編輯的代碼如下:

from PIL import Image 
from PIL import ImageColor 



path_to_file = 'data.txt' 

img_data = [] 
height = 0 
width = 0 

# The first step is to read the file 
with open(path_to_file) as f: 
    lines = f.readlines() 

# Strip off new lines 
lines = [x.strip('\n') for x in lines] 



for line in lines: 
    x,y = line[:-7].split(',') 

    # I'm assuming from the data that the x,y vals start at 1,1. Subtract 1 from each value so they are zero indexed. 
    x = int(x) - 1 
    y = int(y) - 1 

    color = line[-7:] 

    # Use PIL's ImageColor.getrgb() to convert hex string to a rgb tuple 
    color = ImageColor.getrgb(color) 

    img_data.append((x,y,color)) 


    # Keep track of the max x,y vals for to get the width and height of the image 
    height = max(height, x+1) 
    width = max(width, y+1) 

# Create a new image 
background = (0, 0, 0, 255) 
img = Image.new('RGB', (width, height), background) 
pixels = img.load() 

# Set the pixel values from our data 
for d in img_data: 
    pixels[d[0], d[1]] = d[2] 


img.save("image.png") 

現在提出:

ValueError: too many values to unpack 

如何解決這個問題?

+1

如果你想在這方面幫助,你應該張貼自己的代碼的嘗試,並解釋清楚,你就完蛋了。這個任務相當直接,特別是像像素列表的排序方式,就像您的示例數據一樣。 –

回答

0

這爲我工作:

from PIL import Image 
from PIL import ImageColor 



path_to_file = 'test.txt' 

img_data = [] 
height = 0 
width = 0 

# The first step is to read the file 
with open(path_to_file) as f: 
    lines = f.readlines() 

# Strip off new lines 
lines = [x.strip('\n') for x in lines] 



for line in lines: 
    x,y = line[:-7].split(',') 

    # I'm assuming from the data that the x,y vals start at 1,1. Subtract 1 from each value so they are zero indexed. 
    x = int(x) - 1 
    y = int(y) - 1 

    color = line[-7:] 

    # Use PIL's ImageColor.getrgb() to convert hex string to a rgb tuple 
    color = ImageColor.getrgb(color) 

    img_data.append((x,y,color)) 


    # Keep track of the max x,y vals for to get the width and height of the image 
    height = max(height, y) 
    width = max(width, x) 

# Create a new image 
background = (0, 0, 0, 255) 
img = Image.new('RGB', (width + 1, height + 1), background) 
pixels = img.load() 

# Set the pixel values from our data 
for d in img_data: 
    pixels[d[0], d[1]] = d[2] 


img.save("image.png") 
+0

thx但它說「太多的值來解包」 – hckn0

+0

@ hckn0如果您可以發佈實際的錯誤消息,我可以幫助你更好。而且,如果沒有您的完整數據,我無法知道什麼是錯的。 – LeopoldVonBuschLight

+0

@ hckn0查看更新的代碼 – LeopoldVonBuschLight