【问题标题】:How do I create an image in PIL using a list of RGB tuples?如何使用 RGB 元组列表在 PIL 中创建图像?
【发布时间】:2012-08-17 06:35:00
【问题描述】:

假设我在一个看起来像 list(im.getdata()) 的列表中有一个像素列表(表示为具有 3 个 RGB 值的元组),如下所示:

[(0,0,0),(255,255,255),(38,29,58)...]

如何使用这种格式的 RGB 值(每个元组对应一个像素)创建新图像?

感谢您的帮助。

【问题讨论】:

  • 我尝试使用im.paste(),但它给了我以下错误:“SystemError: New style getargs format but argument is not a tuple”

标签: python python-imaging-library


【解决方案1】:

你可以这样做:

list_of_pixels = list(im.getdata())
# Do something to the pixels...
im2 = Image.new(im.mode, im.size)
im2.putdata(list_of_pixels)

【讨论】:

    【解决方案2】:

    您也可以为此使用scipy

    #!/usr/bin/env python
    
    import scipy.misc
    import numpy as np
    
    # Image size
    width = 640
    height = 480
    channels = 3
    
    # Create an empty image
    img = np.zeros((height, width, channels), dtype=np.uint8)
    
    # Draw something (http://stackoverflow.com/a/10032271/562769)
    xx, yy = np.mgrid[:height, :width]
    circle = (xx - 100) ** 2 + (yy - 100) ** 2
    
    # Set the RGB values
    for y in range(img.shape[0]):
        for x in range(img.shape[1]):
            r, g, b = circle[y][x], circle[y][x], circle[y][x]
            img[y][x][0] = r
            img[y][x][1] = g
            img[y][x][2] = b
    
    # Display the image
    scipy.misc.imshow(img)
    
    # Save the image
    scipy.misc.imsave("image.png", img)
    

    给予

    【讨论】:

    • Scipy 仅在您首先安装了 PIL 时才会安装图像功能 :(
    • 漂亮的图片...我喜欢它!
    【解决方案3】:

    这是一个完整的例子,因为我一开始没明白。

    from PIL import Image
    
    img = Image.new('RGB', [500,500], 255)
    data = img.load()
    
    for x in range(img.size[0]):
        for y in range(img.size[1]):
            data[x,y] = (
                x % 255,
                y % 255,
                (x**2-y**2) % 255,
            )
    
    img.save('image.png')
    

    如果你只寻找灰度,你可以先Image.new('L', [500,500], 255) 然后data[x,y] = <your value between 0 and 255>

    【讨论】:

      猜你喜欢
      • 2020-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-11
      • 2018-06-25
      • 1970-01-01
      • 2013-11-01
      相关资源
      最近更新 更多