Reputation: 1104
I have numpy array:
>> print(data[0].shape)
(3, 5, 5)
which corresponds to 5x5
RGB image. When I try plt.imshow(data[0])
I get TypeError: Invalid dimensions for image data
. How to properly show this image?
Upvotes: 1
Views: 7397
Reputation: 1307
The first problem is with the order of your axis.
As Divakar commented, you can swap your axes first and the you can use OpenCV to show it on a window instead of using MPL which will show you the real colors.
import cv2
data = data.swapaxes(0,2)
cv2.imshow('image',data)
cv2.waitKey(0)
However, if you want to use a MPL with colormap as Xenatisch proposed, you can change your matrix from RGB to Grayscale with OpenCV and then use imshow
import cv2
from matplotlib import pyplot as plt
data = data.swapaxes(0,2)
gray_data = cv2.cvtColor(data, cv2.COLOR_BGR2GRAY) # from (5x5x3) to (5x5) matrix, perfect for plotting!
plt.imshow(gray_data, cmap = 'gray', interpolation = 'nearest')
plt.xticks([]), plt.yticks([])
plt.show()
You can use any other colormap that you want. Take into account that I assume that your depth colors are on BGR format. If they are in another order, roll or make the required changes ;)
On all cases the swap axes is required as the order should be (height,width,depth), and you have (depth,height,width)
Upvotes: 0
Reputation: 1091
This appears to be a 3 dimensional matrix, not a 5x5 image.
A 5x5 RGB image would appears like this:
a1 a2 a3 a4 a5
b1 b2 b3 b4 b5
c1 c2 c3 c4 c5
d1 d2 d3 d4 d5
e1 e2 e3 e4 e5
What you are showing, is 3 dimensions matrix, in which the 3rd dimension does not correspond to any volume (as in 3d images) either. Hence the invalid dimensions
error. What you want to do is to incorporate into an n * m matrix the RGB numbers you want to display, such that X_{r:j}=RGB. Then you can display the matrix as an image.
Example of image matrices:
from numpy.random import rand
from matplotlib.pyplot import imshow
img = rand(5, 5) # Creating a 5x5 matrix of random numbers.
# Use bilinear interpolation (or it is displayed as bicubic by default).
imshow(img, interpolation="nearest")
show()
Displays:
Of course the numbers in this matrix do not correspond to RGB colours, but intensity, and are displayed through the default colourmap
(Jet). But I'm sure you get the idea.
Upvotes: 1