Reputation: 2059
I have a muti lined .txt file with image data like this:
(198, 252, 247) (255, 255, 250) (254, 253, 248) (251, 252, 246) (247, 248, 240) ...
(100, 144, 247) (255, 200, 250) (254, 253, 248) (251, 252, 246) (247, 248, 240) ...
How do I read these data into tuples?
lst = [((198, 252, 247), (255, 255, 250)), (second line), (thrid) ...]
and eventually draw each line back into an image file using the Image
module
Upvotes: 1
Views: 6583
Reputation: 3850
Simply read each line, extract the value triplets from it, and convert them to integers.
import re
triplet = r'\((\d+), (\d+), (\d+)\)' # regex pattern
image = []
with open('image.txt') as fp:
for line in fp:
image.append([(int(x), int(y), int(z)) for x, y, z in re.findall(triplet, line)])
EDIT
To actually draw the image, check out this question. However, this should work:
from PIL import Image
width, height = len(image[0]), len(image)
data = sum(image, []) # ugly hack to flatten the image
im = Image.new('RGB', (width, height))
im.putdata(data)
im.save('image.png')
Upvotes: 2
Reputation: 943
First you need to scan and split the data from the file, then you can just parse the tuples from the data (string tuple), then simply create an image object using PIL
def getTuple(s):
try:
s = eval(str(s))
if type(s) == tuple:
return s
return
except:
return
with open("filename.txt", "rb") as fp:
im_list = []
data_points = fp.read()
data_point_list = data_points.split("-")
for data_point in data_point_list:
im_list.append(getTuple(data_point))
# the code snippet from https://stackoverflow.com/questions/12062920/how-do-i-create-an-image-in-pil-using-a-list-of-rgb-tuples
im2 = Image.new(im.mode, im.size)
im2.putdata(list_of_pixels)
Upvotes: 0