首页 > 解决方案 > 如何在python中生成每个像素都是随机颜色的图像

问题描述

我正在尝试为每个像素制作具有随机颜色的图像,然后打开一个窗口来查看图像。

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 

标签: pythonimageimage-processingrandomcolors

解决方案


数组可以组装成一行:

import numpy as np
from PIL import Image

arr = np.random.randint(low = 0, high = 255, size = (300, 300, 3))

im = Image.fromarray(arr.astype('uint8'))
im.show()

输出:

在此处输入图像描述


推荐阅读