python从RGB元组创建图像

问题描述 投票:0回答:2

我有一个多行.text文件,其中的图像数据如下:

(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) ... 

如何将这些数据读入元组?

lst = [((198, 252, 247), (255, 255, 250)), (second line), (thrid) ...]

并最终使用Image模块将每一行绘制回图像文件

python image drawing draw
2个回答
2
投票

只需读取每一行,从中提取值三元组,并将它们转换为整数。

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

编辑

要实际绘制图像,请查看this question。但是,这应该工作:

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

0
投票

首先,您需要扫描并拆分文件中的数据,然后您只需从数据中解析元组(字符串元组),然后使用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)
© www.soinside.com 2019 - 2024. All rights reserved.