pythonopencvfftmagnitude

OpenCV/Python: Colorbar in fft magnitude


I'm using opencv in python 2.7.

  1. The colormap is oversized. How to shrink it to has the same length as the image?
  2. How do I explain the value/range of magnitude?

This is my code:

import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('messi.jpg',0)

dft = cv2.dft(np.float32(img),flags = cv2.DFT_COMPLEX_OUTPUT)
dft_shift = np.fft.fftshift(dft)

magnitude_spectrum = np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1]))

plt.subplot(131),plt.imshow(img, cmap = 'gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(132),plt.imshow(magnitude_spectrum, cmap = 'gray'), plt.colorbar(cmap = 'gray')
plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
plt.show() 

enter image description here


Solution

  • I found the solution.

    To resize the colorbar I use fraction parameter and it's corresponding value in colorbar. Thanks to bejota's answer.

    Regarding the magnitude value, I found that as brighter are the vertices in the magnitude image the greater the contrast in brightness of the original grayscale image. Try the code below using various images.

    This is my final code:

    import numpy as np
    import cv2
    from matplotlib import pyplot as plt
    
    img = cv2.imread('messi.jpg',0)
    
    dft = cv2.dft(np.float32(img),flags = cv2.DFT_COMPLEX_OUTPUT)
    dft_shift = np.fft.fftshift(dft)
    
    magnitude_spectrum = np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1]))
    
    
    plt.subplot(121),plt.imshow(img, cmap = 'gray')
    plt.title('Input Image'), plt.xticks([]), plt.yticks([])
    plt.subplot(122),plt.imshow(magnitude_spectrum, cmap = 'gray'), plt.colorbar(cmap = 'gray',fraction=0.03, pad=0.04)
    plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
    plt.show() 
    

    And this is the result: enter image description here