简体   繁体   English

如何将列表(或 numpy 数组或矩阵)转换为图像?

[英]How to transform a list (or numpy array or matrix) into an image?

I have a huge table (or matrix, if you want).我有一张巨大的桌子(或矩阵,如果你愿意的话)。 I would like to visualize this table by making an image in which each pixel corresponds to a cell in the table (so, the row and columns in the table corresponds to the "rows" and "columns" of the pixels in the image).我想通过制作一个图像来可视化这个表格,其中每个像素对应于表格中的一个单元格(因此,表格中的行和列对应于图像中像素的“行”和“列”)。

The values in the cells corresponds already to the colors (for example [255, 0, 0] is the value that corresponds to red).单元格中的值已经对应于颜色(例如[255, 0, 0]是对应于红色的值)。 In other words, each cell in the table contains a 3 dimensional vector representing a color.换句话说,表格中的每个单元格都包含一个表示颜色的 3 维向量。

The table can be represented as a list of lists of lists or as a 3D numpy array.该表可以表示为列表列表或 3D numpy数组。

You can use matplotlib's imshow function to do this.您可以使用matplotlib's imshow函数来执行此操作。 You just need to normalise your array from 0 - 255 to 0 - 1 , then you can feed imshow your MxNx3 array.您只需要将数组从0 - 255标准化为0 - 1 ,然后您就可以imshow您的MxNx3数组。

Here's a simple example:这是一个简单的例子:

import matplotlib.pyplot as plt
import numpy as np

fig,ax=plt.subplots(1,subplot_kw={'aspect':'equal'})

# A small 3x3 sample array
imarray=np.array([
    [[255,0,0],[0,255,0],[0,0,255]],
    [[255,255,0],[0,255,255],[255,0,255]],
    [[255,255,255],[127,127,127],[0,0,0]]
    ])

# Normalise the data to between 0 and 1
imarray = imarray.astype('float')/255.

# plot the array
ax.imshow(imarray,interpolation='nearest')

plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM