简体   繁体   中英

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. 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.

Here is an example image, the array is 28x28 and contains values between 0 and 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.

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:

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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