簡體   English   中英

你如何在python中生成每個像素都是隨機顏色的圖像

[英]How do you generate an image where each pixel is a random color in 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 

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

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

im = Image.fromarray(arr)
im.show()

輸出:

在此處輸入圖像描述

首先創建您的 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')

這對我有用這是圖片

在此處輸入圖像描述

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

暫無
暫無

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

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