【问题标题】:How to create image from a list of pixel values in Python3?如何从 Python3 中的像素值列表创建图像?
【发布时间】:2017-10-25 03:00:15
【问题描述】:

如果我有以下格式的图像的像素行列表,如何获取图像?

[
   [(54, 54, 54), (232, 23, 93), (71, 71, 71), (168, 167, 167)],
   [(204, 82, 122), (54, 54, 54), (168, 167, 167), (232, 23, 93)],
   [(71, 71, 71), (168, 167, 167), (54, 54, 54), (204, 82, 122)],
   [(168, 167, 167), (204, 82, 122), (232, 23, 93), (54, 54, 54)]
]

【问题讨论】:

    标签: python python-3.x python-imaging-library python-3.6 pillow


    【解决方案1】:

    PILnumpy 是你的朋友:

    from PIL import Image
    import numpy as np
    
    
    pixels = [
       [(54, 54, 54), (232, 23, 93), (71, 71, 71), (168, 167, 167)],
       [(204, 82, 122), (54, 54, 54), (168, 167, 167), (232, 23, 93)],
       [(71, 71, 71), (168, 167, 167), (54, 54, 54), (204, 82, 122)],
       [(168, 167, 167), (204, 82, 122), (232, 23, 93), (54, 54, 54)]
    ]
    
    # Convert the pixels into an array using numpy
    array = np.array(pixels, dtype=np.uint8)
    
    # Use PIL to create an image from the new array of pixels
    new_image = Image.fromarray(array)
    new_image.save('new.png')
    

    编辑:

    numpy 制作随机像素的图像有点乐趣:

    from PIL import Image
    import numpy as np
    
    def random_img(output, width, height):
    
        array = np.random.random_integers(0,255, (height,width,3))  
    
        array = np.array(array, dtype=np.uint8)
        img = Image.fromarray(array)
        img.save(output)
    
    
    random_img('random.png', 100, 50)
    

    【讨论】:

    • 太棒了!编辑我的帖子以获得一点列表理解的乐趣,以制作具有随机像素值的图像。
    • 很好的答案,但对于大分辨率,它需要相当长的时间(随机像素),所以我虽然我应该尝试优化它(以前从未做过)。我所做的唯一修改是,我只调用了一次,而不是列表理解和调用函数 width*height*3 次。数组 = np.random.random_integers(0,255, (width,height,3)) 。祝你有美好的一天:)
    • 注意到了。我会为遇到此问题的其他人更新我的答案。
    【解决方案2】:

    我自己没有使用过 PIL,但最好的方法是使用 PIL 打开一个实际的图像文件。然后探索打开所述图像所涉及的 API 和对象,并查看像素值如何存储在与 API 相关的特定对象中。

    然后,您可以使用提取的 RGB 值构造一个有效的 PIL 图像对象。

    编辑: 请参阅以下帖子:How do I create an image in PIL using a list of RGB tuples?

    附加,在 PIL 中访问像素值:https://pillow.readthedocs.io/en/4.3.x/reference/PixelAccess.html

    【讨论】:

    • 谢谢,但我之前已经看过这些帖子,但我仍然不明白如何根据我拥有的值创建图像。我知道您可以使用 getdata() 从图像中提取像素值,但是如何仅从像素值列表中创建新图像?
    猜你喜欢
    • 2015-09-05
    • 2012-09-14
    • 2020-09-18
    • 1970-01-01
    • 2014-12-25
    • 2015-05-30
    • 1970-01-01
    • 2011-06-20
    • 2015-04-24
    相关资源
    最近更新 更多