Im trying to show a simple RGB array using pyplot.imshow. However it behaves unexpectedly, for example for a pixel value (1,1,1) is shown as completely white, (0,0,0) as completely black and also value close to (255,255,255) are also shown as black. Whats going on here. Is the input matrix getting somehow scaled pixel-wise?
1 Answer
It sounds like your array has floating-point dtype. Change it to unsigned 8-bit ints (uint8
):
arr = arr.astype('uint8')
import numpy as np import matplotlib.pyplot as plt float_arr = np.array([[(1,1,1),(0,0,0)], [(0,0,0),(255,255,255)]], dtype='float32') int_arr = np.array([[(1,1,1),(0,0,0)], [(0,0,0),(255,255,255)]], dtype='uint8') fig, ax = plt.subplots(ncols=2) ax[0].imshow(float_arr) ax[0].set_title('float32') ax[1].imshow(int_arr) ax[1].set_title('uint8') plt.legend() plt.show()
The image on the left replicates the behavior you are seeing. The image on the right is what you'd get if your array had uint8
dtype.
Per the docs, imshow
can accept an MxNx3
RGB array of either floating-point or uint8 dtype.
However, if the array has floating-point dtype, the values are expected to be between 0.0 and 1.0.
If the array has uint8
dtype, then the values are expected to be between 0 and 255.
- Yeah, this is what's going on, but what got me confused is that the one that expects values to be in range <0.0, 1.0> is neither clipping the 0-255 values, nor scalling them down to fit the range.– LugiCommentedAug 1, 2017 at 0:25
imshow
.