具有随机像素颜色的100x100图像

Ice*_*gon 10 python image matplotlib draw python-imaging-library

我正在尝试制作一个100x100图像,每个像素都是不同的随机颜色,如下例所示:

在此输入图像描述

我试过用,matplotlib但我运气不好.我应该使用PIL吗?

Hoo*_*ked 25

numpy和简单这很简单pylab.您可以将色彩映射设置为您喜欢的任何颜色,这里我使用光谱.

from pylab import imshow, show, get_cmap
from numpy import random

Z = random.random((50,50))   # Test data

imshow(Z, cmap=get_cmap("Spectral"), interpolation='nearest')
show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

您的目标图像看起来具有像素密度高于100x100的灰度色彩图:

import pylab as plt
import numpy as np

Z = np.random.random((500,500))   # Test data
plt.imshow(Z, cmap='gray', interpolation='nearest')
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


hel*_*ker 20

如果你想创建一个图像文件(并在其他地方显示,有或没有Matplotlib),你可以使用Numpy和PIL,如下所示:

import numpy, Image

imarray = numpy.random.rand(100,100,3) * 255
im = Image.fromarray(imarray.astype('uint8')).convert('RGBA')
im.save('result_image.png')
Run Code Online (Sandbox Code Playgroud)

这里的想法是创建一个数字数组,将其转换为RGB图像,并将其保存到文件.如果你想要灰度图像,你应该使用convert('L')而不是convert('RGBA').

希望这可以帮助

  • 你的意思是`来自PIL import Image`? (4认同)

Pau*_*McG 6

我想写一些简单的BMP文件,所以我研究了格式并写了一个非常简单的bmp.py模块

# get bmp.py at http://www.ptmcg.com/geo/python/bmp.py.txt
from bmp import BitMap, Color
from itertools import product
from random import randint, choice

# use a set to make 256 unique RGB tuples
rgbs = set()
while len(rgbs) < 256:
    rgbs.add((randint(0,255), randint(0,255), randint(0,255)))

# convert to a list of 256 colors (all you can fit into an 8-bit BMP)
colors = [Color(*rgb) for rgb in rgbs]

bmp = BitMap(100, 100)
for x,y in product(range(100), range(100)):
    bmp.setPenColor(choice(colors))
    bmp.plotPoint(x, y)

bmp.saveFile("100x100.bmp", compress=False)
Run Code Online (Sandbox Code Playgroud)

示例 100x100.bmp:

100x100.bmp

对于稍大的像素大小,请使用:

PIXEL_SIZE=5
bmp = BitMap(PIXEL_SIZE*100, PIXEL_SIZE*100)
for x,y in product(range(100), range(100)):
    bmp.setPenColor(choice(colors))
    bmp.drawSquare(x*PIXEL_SIZE, y*PIXEL_SIZE, PIXEL_SIZE, fill=True)

filename = "%d00x%d00.bmp" % (PIXEL_SIZE, PIXEL_SIZE)
bmp.saveFile(filename)
Run Code Online (Sandbox Code Playgroud)

500x500.bmp

您可能不想使用 bmp.py,但这向您展示了您需要做什么的总体思路。


ban*_*013 6

import numpy as np
import matplotlib.pyplot as plt

img = (np.random.standard_normal([28, 28, 3]) * 255).astype(np.uint8)

# see the raw result (it is 'antialiased' by default)
_ = plt.imshow(img, interpolation='none')
# if you are not in a jupyter-notebook
plt.show()
Run Code Online (Sandbox Code Playgroud)

会给你这个 28x28 RGB 图像:

图片