Search code examples
pythonmatplotlibimshow

plt.imshow() of a single color image showing as black


I am trying to show a light-gray image using plt.imshow(), but the image turns out black.

I tried:

import matplotlib.pyplot as plt
import numpy as np
test_image = np.zeros((3871, 2484))
test_image.fill(200)
plt.imshow(test_image, cmap="gray")
plt.show()

But ended up getting:

A black image

  • Matplotlib version: 3.7.1
  • Numpy version: 1.24.3
  • Python version: 3.11.3

Solution

  • You have to include the vmin,vmax parameters when you plot a single color image with plt.imshow(...). Set vmin=0 and vmax=500 to get a gray image. If vmin,vmax are not specified, then they will be set to the min and max values of the image data. This means that all of your input data is equal to vmin, which is the darkest possible value (black).

    import matplotlib.pyplot as plt
    import numpy as np
    
    test_image = np.zeros((3871, 2484))
    test_image.fill(200)
    plt.imshow(test_image, cmap="gray", vmin=0, vmax=500)
    plt.show()