Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib imshow() using 3xN RGB array

Tags:

python

numpy

I use custom 3xN data with value range (0, 1) as RGB color, and want to use matplotlib.imshow() to show it.

import pylab as plt
import numpy as np

Z = np.vstack([np.zeros((1, 256)), np.zeros((1, 256,)), np.zeros((1, 256,))])
im = plt.imshow(Z, interpolation='none', aspect='auto')
plt.colorbar(im, orientation='horizontal')
plt.show()

I expect this to give me a black image. But instead I get a green one like this: enter image description here

And the Y-ticks look funny. I don't understand the -0.5 tick on the Y-axis at all. Why does the y-axis range between [-0.5, 2.5]?

like image 934
kakyo Avatar asked Sep 02 '25 08:09

kakyo


2 Answers

For anybody landing on this page several years out, OP figured out the reasons for the initial issue but the easier fix is: np.dstack(). numpy.dstack

import numpy as np
import matplotlib.pyplot as plt

Z = np.vstack([np.zeros((1, 256)), np.zeros((1, 256,)), np.zeros((1, 256,))])
im = plt.imshow(np.dstack(Z), interpolation='none', aspect='auto')
plt.colorbar(im, orientation='horizontal')
plt.show()

result

like image 96
Beethoven's 7th Avatar answered Sep 04 '25 21:09

Beethoven's 7th


Figured it out myself:

  1. imshow() expect the input data array size to be 1 x N x 3. 3 refers to RGB.
  2. Because my data was 3 x N, imshow() considered it three data, hence the [-0.5, 2.5] simply reflects three vertically-stacked data rows, each spanning a 0~1.0 range.

Here is a simple fix:

import pylab as plt
import numpy as np

Z = np.vstack([np.zeros((1, 256)), np.zeros((1, 256,)), np.zeros((1, 256,))]).transpose()
Z = Z[None, ...]
im = plt.imshow(Z, interpolation='none', aspect='auto')
plt.colorbar(im, orientation='horizontal')
plt.show()
like image 45
kakyo Avatar answered Sep 04 '25 20:09

kakyo