Home > Mobile >  Trouble when printing a subplot in pyhton in gray scales (something not working)
Trouble when printing a subplot in pyhton in gray scales (something not working)

Time:07-28

I was trying to take any image and show it and its respective fftshifted version. In this process, I would like to produce both images in black and white only (or gray scales...). Currently I have the following code:

from matplotlib import image
import matplotlib.pyplot as plt
import numpy as np

cameraman = image.imread("cameraman.png")

fftshifted_cameraman = np.fft.fftshift(cameraman)

fig1 = plt.figure()

ax11 = fig1.add_subplot(121)
plt.axis('off')
plt.imshow(cameraman, cmap = 'gray')
ax11.title.set_text('Cameraman')

ax12 = fig1.add_subplot(122)
plt.axis('off')
plt.imshow(fftshifted_cameraman, cmap = 'gray')
ax12.title.set_text('FFT Shifted Cameraman')

plt.show()

This gives me the following output:

enter image description here

Obviously, the second image is clearly not in gray scales and I believe the first one is only because it is like that by default. Does anyone know how to fix this?

Thanks for any help in advance.

CodePudding user response:

To produce gray scale images with imshow(), you need to pass 2-D arrays. Check the shape of image array and if it is 3-D (or 4-D with alpha channel) then convert:

cameraman_gray = cameramen[:,:,0]
plt.imshow(cameraman_gray, cmap='gray')
  • Related