簡體   English   中英

如何使用RGB元組列表在PIL中創建圖像?

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

假設我在看起來像list(im.getdata())的列表中有一個像素列表(表示為具有3個RGB值的元組list(im.getdata()) ,如下所示:

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

如何使用這種格式的RGB值(每個元組對應一個像素)創建新圖像?

謝謝你的幫助。

您可以這樣做:

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

您也可以使用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)

在此處輸入圖片說明

這是一個完整的示例,因為我一開始並沒有掌握竅門。

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM