【问题标题】:How do you generate an image where each pixel is a random color in python如何在python中生成每个像素都是随机颜色的图像
【发布时间】:2020-03-22 04:25:09
【问题描述】:

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

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 

【问题讨论】:

    标签: python image image-processing random colors


    【解决方案1】:

    数组可以组装成一行:

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

    输出:

    【讨论】:

    • 写得好 :) 你的回答很清楚,很容易理解,竖起大拇指
    【解决方案2】:

    PIL Image 是一个 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()
    

    【讨论】:

      【解决方案3】:

      首先创建你的 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')
      

      这对我有用

      【讨论】:

        猜你喜欢
        • 2021-10-01
        • 2021-09-26
        • 1970-01-01
        • 1970-01-01
        • 2019-03-18
        • 1970-01-01
        • 2022-11-26
        • 1970-01-01
        • 2018-04-02
        相关资源
        最近更新 更多