I'm trying to plot a numpy array with shape [height x width x 3] containing RGB values. As a simple example suppose you have the Belgian flag:
import numpy as np
import matplotlib.pyplot as plt
flag = np.empty((1,3,3))
flag[0,0,:] = (0,0,0)
flag[0,1,:] = (254,240,71)
flag[0,2,:] = (255,55,14)
plt.imshow(flag)
plt.show()
This results in the following output:

Can anyone tell me why it is not plotting the right RGB values? Did I make a mistake in the dimensionality? Probably an easy answer to this, but can't seem to find it .. Thanks a lot for any advice!
The default data type for the array created by numpy.empty is floating point, and imshow treats floating point values differently than integer values. (imshow expects floating point values to be in the range 0.0 to 1.0.)
Change this
flag = np.empty((1,3,3))
to
flag = np.empty((1,3,3), dtype=np.uint8)
The reason you got those particular colors when flag is floating point is that imshow apparently converted your array to integer without checking that the input values were in the range 0.0 to 1.0. Here's what happens in that case:
In [25]: flag
Out[25]:
array([[[ 0., 0., 0.],
[ 254., 240., 71.],
[ 255., 55., 14.]]])
In [26]: img = (flag*255).astype(np.uint8)
In [27]: img
Out[27]:
array([[[ 0, 0, 0],
[ 2, 16, 185],
[ 1, 201, 242]]], dtype=uint8)
If you then run imshow(img), you get the black, blue and cyan plot.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With