如何在Python中生成每个像素都是随机颜色的图像

3
我正在尝试为每个像素制作一个随机颜色的图像,然后打开一个窗口查看该图像。
import PIL, random
import matplotlib.pyplot as plt 
import os.path  
import PIL.ImageDraw            
from PIL import Image, ImageDraw, ImageFilter


im = Image.new("RGB", (300,300))

for r in range(0,300):
    for c in range(0,300):
        re = random.randint(0, 255)
        gr = random.randint(0, 255)
        bl = random.randint(0, 255)
        im[r][c]=[re,gr,bl]
im.show()

     14         bl = random.randint(0, 255)
---> 15         im[r][c]=[re,gr,bl]
     16 im.show()
TypeError: 'Image' object does not support indexing 
3个回答

10

你可以使用numpy.random.randint在一行中高效地组装所需的数组。

import numpy as np
from PIL import Image

# numpy.random.randint returns an array of random integers
# from low (inclusive) to high (exclusive). i.e. low <= value < high

pixel_data = np.random.randint(
    low=0, 
    high=256,
    size=(300, 300, 3),
    dtype=np.uint8
)

image = Image.fromarray(pixel_data)
image.show()

输出:

enter image description here


3
写得很好 :) 你的回答非常清晰易懂,点个赞。 - ThunderHorn

1
首先创建你的numpy数组,然后将其放入PIL中。
import numpy as np
from random import randint
from PIL import Image

array = np.array([[[randint(0, 255),randint(0, 255),randint(0, 255)]] for i in range(100)])
array =  np.reshape(array.astype('uint8'), (10, 10, 3))
img = Image.fromarray(np.uint8(array.astype('uint8')))

img.save('pil_color.png')

这对我有用:

这是图片

enter image description here


0
PIL Image 是一个图像对象,你不能直接将这些值注入到指定的像素中。相反,需要先将其转换为数组,然后以 PIL 图像的形式显示出来。
import random
import numpy as np
from PIL import Image

im = Image.new("RGB", (300,300))
im = np.array(im)

for r in range(0,300):
    for c in range(0,300):
        re = random.randint(0, 255)
        gr = random.randint(0, 255)
        bl = random.randint(0, 255)
        im[r][c]=[re,gr,bl]
img = Image.fromarray(im, 'RGB')

img.show()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接