2017-07-03 526 views

回答

1

matplotlib对于像这样的任务很有用,尽管还有其他方法。 下面是一个例子:

import numpy as np 
import matplotlib.image 

src = np.zeros((200,200)) 
print src.shape 

rgb = np.zeros((200,200,3)) 
print rgb.shape 

src[10,10] = 1 
src[20,20] = 2 
src[30,30] = 3 

for i in range(src.shape[0]): 
    for j in range(src.shape[1]): 
    rgb[i,j,0] = 255 if src[i,j]==1 else 0 # R 
    rgb[i,j,1] = 255 if src[i,j]==2 else 0 # G 
    rgb[i,j,2] = 255 if src[i,j]==3 else 0 # B 

matplotlib.image.imsave('test.png', rgb.astype(np.uint8)) 

诀窍是将其转换为形状(x, y, 3)的RGB阵列。您可以使用任何想要生成每像素RGB值的公式。

此外,请注意将其转换为uint8阵列。

+1

谢谢先生......我已经这样做了。 –

+1

不是问题!你能接受我的回答吗? – keredson

+1

先生,我是在stackoverflow.com上新注册的。只要我的声望超过15,我已经接受了你的回答。我的接受将会出现。再次感谢你帮助我 –

1

你可以使用PIL.Image来做到这一点,但首先转换你的数组。

可以说,例如,认为:

  1. 1.0应该是红色,表示为(255,0,0)
  2. 2.0应该是绿色 - >(0,255,0)
  3. 3.0应为蓝色 - >(0,0,255)
  4. 4.0应该是黑色的 - >(0,0,0)
  5. 5.0应该是白色 - >(255,255,255)

当然,您可以将这些值更改为您选择的任何颜色,但这仅用于演示。话虽如此,你的二维数组也需要被“扁平化”为1-d,以便PIL.Image将其作为数据接受。

from PIL import Image 
import numpy as np 
your_2d_array = np.something() # Replace this line, obviously 
img_array = [] 
for x in your_2d_array.reshape(2000*2000): 
    if x == 1.0: 
     img_array.append((255,0,0)) # RED 
    elif x == 2.0: 
     img_array.append((0,255,0)) # GREEN 
    elif x == 3.0: 
     img_array.append((0,0,255)) # BLUE 
    elif x == 4.0: 
     img_array.append((0,0,0)) # BLACK 
    elif x == 5.0: 
     img_array.append((255,255,255)) # WHITE 

img = Image.new('RGB',(2000,2000)) 
img.putdata(img_array) 
img.save('somefile.png') 

虽然这应该工作,我觉得有更有效的方式来做到这一点,我不知道,所以,如果有人编辑这个答案有更好的例子,我会很高兴。但如果它是一个小应用程序,并且最大的效率不会打扰你,那么就是这样。

+1

谢谢Ofer Sadan ... –

相关问题