2013-03-07 146 views
6

我试图与每个像素是一个不同的随机颜色,像这样的例子一100x100图像:100x100的图像具有随机的像素颜色

enter image description here

我试着使用matplotlib但我没有太多的运气。我应该使用PIL吗?

+2

你有什么特别的尝试? – tacaswell 2013-03-07 02:14:55

+1

(也就是说,确保发布当前代码/尝试,并描述它们如何不按预期工作。) – 2013-03-07 02:17:48

回答

19

这很简单,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() 

enter image description here

你的目标图像看起来有一个更高的像素密度的灰度色彩表比100×100:

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

enter image description here

+0

如何将这些图像保存为ubuntu上的文件? – raitisd 2017-08-22 13:28:51

+1

@raitisd保存图像使用['savefig'](https://matplotlib.org/api/pyplot_api.html?highlight=matplotlib%20pyplot%20savefig#matplotlib.pyplot.savefig) – Hooked 2017-08-22 17:57:36

13

如果你想创建一个图像文件(并在其他地方显示,有或没有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') 

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

希望这有助于

+1

您的意思是'从PIL导入图像' ? – 2018-02-01 22:51:59

3

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

# 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 

# make a list of 256 colors (all you can fit into an 8-bit BMP) 
colors = [Color(randint(0,255), randint(0,255), randint(0,255)) 
       for i in xrange(256)] 

bmp = BitMap(100,100) 
for x,y in product(xrange(100),xrange(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(xrange(100),xrange(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,但是这说明你的,你需要做的总体思路。

1

我相信阵列的彩色地图为骨,即

#import the modules 
import numpy as np 
import matplotlib.cm as cm 
import matplotlib.pyplot as plt 

rand_array=np.random.rand(550,550) #create your array 
plt.imshow(rand_array,cmap=cm.bone) #show your array with the selected colour 
plt.show() #show the image 

应该产生你在找什么:)

编辑:只是改变550到100,如果你想有一个100×100 array