100x100随机像素颜色图像

19 投票
5 回答
57974 浏览
提问于 2025-04-17 18:13

我想制作一张 100x100 的图片,每个像素都用不同的随机颜色,就像这个例子:

在这里输入图片描述

我试过用 matplotlib,但效果不是很好。是不是应该用 PIL 呢?

5 个回答

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)

这是一个示例文件,名为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)

500x500.bmp

你可能不想使用bmp.py,但这个例子可以让你了解你需要做的基本思路。

39

如果你想创建一个图片文件(并且可以在其他地方显示它,不管是否使用Matplotlib),你可以用NumPy和Pillow来做到这一点,方法如下:

import numpy
from PIL import Image

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

这里的思路是先创建一个数字数组,然后把它转换成RGB格式的图片,最后保存到文件里。如果你想要的是灰度图像,那就应该用 convert('L'),而不是 convert('RGBA')

28

这很简单,只需要用到 numpypylab。你可以把颜色映射设置成你喜欢的样子,这里我用的是光谱色。

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

这里输入图片描述

你想要的目标图像看起来是灰度颜色映射,而且像素密度比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()

这里输入图片描述

撰写回答