简体   繁体   English

给定一个2D numpy实数数组,如何生成描绘每个数字强度的图像?

[英]Given a 2D numpy array of real numbers, how to generate an image depicting the intensity of each number?

I have a 2D numpy array and would like to generate an image such that the pixels corresponding to numbers that have a high value (relative to other pixels) are coloured with a more intense colour. 我有一个2D numpy数组,并希望生成一个图像,使得对应于具有高值(相对于其他像素)的数字的像素用更强烈的颜色着色。 For example if the image is in gray scale, and a pixel has value 0.4849 while all the other pixels correspond to values below 0.001 then that pixel would probably be coloured black, or something close to black. 例如,如果图像是灰度级的,并且像素具有值0.4849而所有其他像素对应于低于0.001的值,则该像素可能被着色为黑色,或者接近黑色。

Here is an example image, the array is 28x28 and contains values between 0 and 1. 这是一个示例图像,数组为28x28,包含0到1之间的值。

All I did to plot this image was run the following code: 我绘制此图像的所有操作都运行以下代码:

import matplotlib.pyplot as plt
im = plt.imshow(myArray, cmap='gray')
plt.show()

在此输入图像描述

However, for some reason this only works if the values are between 0 and 1. If they are on some other scale which may include negative numbers, then the image does not make much sense. 但是,出于某种原因,这仅在值介于0和1之间时才有效。如果它们处于可能包含负数的某个其他比例上,则图像没有多大意义。

You can use different colormaps too, like in the example below (note that I removed the interpolation): 您也可以使用不同的色彩映射,如下例所示(请注意我删除了插值):

happy_array = np.random.randn(28, 28)
im = plt.imshow(happy_array, cmap='seismic', interpolation='none')
cbar = plt.colorbar(im)
plt.show()

在此输入图像描述

And even gray is going to work: 甚至灰色也会起作用:

happy_array = np.random.randn(28, 28)
im = plt.imshow(happy_array, cmap='gray', interpolation='none')
cbar = plt.colorbar(im)
plt.show()

在此输入图像描述

You can normalize the data to the range (0,1) by dividing everything by the maximum value of the array: 您可以通过将所有内容除以数组的最大值来将数据规范化到范围(0,1):

 normalized = array / np.amax(a)
 plt.imshow(normalized)

If the array contains negative values you have two logical choices. 如果数组包含负值,则有两个逻辑选择。 Either plot the magnitude: 绘制幅度:

 mag = np.fabs(array)
 normalized = mag / np.amax(mag)
 plt.imshow(normalized)

or shift the array so that everything is positive: 或移动数组,以便一切都是积极的:

positive = array + np.amin(array)
normalized = positive / np.amax(positive)
plt.imshow(normalized)

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

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