简体   繁体   English

如何使用RGB元组列表在PIL中创建图像?

[英]How do I create an image in PIL using a list of RGB tuples?

Suppose I have a list of pixels (represented as tuples with 3 RGB values) in a list that looks like list(im.getdata()) , like this: 假设我在看起来像list(im.getdata())的列表中有一个像素列表(表示为具有3个RGB值的元组list(im.getdata()) ,如下所示:

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

How do I create a new image using RGB values (each tuple corresponds to a pixel) in this format? 如何使用这种格式的RGB值(每个元组对应一个像素)创建新图像?

Thanks for your help. 谢谢你的帮助。

You can do it like this: 您可以这样做:

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

You can also use scipy for that: 您也可以使用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)

gives

在此处输入图片说明

Here's a complete example since I didn't get the trick at first. 这是一个完整的示例,因为我一开始并没有掌握窍门。

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

输出

And if you're looking for grayscale only, you can do Image.new('L', [500,500], 255) and then data[x,y] = <your value between 0 and 255> 如果只寻找灰度,则可以执行Image.new('L', [500,500], 255)然后data[x,y] = <your value between 0 and 255>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM