Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

enter image description here

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.

like image 370
ksm001 Avatar asked Sep 18 '15 19:09

ksm001


People also ask

How do you make a NumPy 2D array?

If you only use the arange function, it will output a one-dimensional array. To make it a two-dimensional array, chain its output with the reshape function. First, 20 integers will be created and then it will convert the array into a two-dimensional array with 4 rows and 5 columns.

How images are represented in NumPy arrays?

Images are an easier way to represent the working model. In Machine Learning, Python uses the image data in the format of Height, Width, Channel format. i.e. Images are converted into Numpy Array in Height, Width, Channel format.

How do I get the dimension of a 2D NumPy array?

You can get the number of dimensions of the NumPy array as an integer value int with the ndim attribute of numpy. ndarray . If you want to add a new dimension, use numpy. newaxis or numpy.


1 Answers

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

enter image description here

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

enter image description here

like image 124
Tarantula Avatar answered Nov 02 '22 18:11

Tarantula