我有一个包含坐标和颜色代码的.txt文件。我想从这个
创建一个图像我的示例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
如何解决此错误?
答案 0 :(得分: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")