1

I am trying to fourier transform an image according to a tutorial I found.

When I try to run my code the following error appears:

Error

I didn't change anything in the tutorial I copied. So I thought there was something wrong with my libraries. I uninstalled Python and all libraries and installed it again. But the error still shows.

My code:

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

img = cv2.imread('C:\Documents\data128.jpg',0)

f = np.fft.fft2(img)
fshift = np.fft.fftshift(f)
magnitude_spectrum = 20*np.log(np.abs(fshift))

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.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
plt.show()

I am using Python 2.7 on Windows 10. Any help is appreciated!

demongolem
  • 9,474
  • 36
  • 90
  • 105

1 Answers1

1

The error occurs because the image has not been loaded. The reason for that is that the file was not found.

You specify the filename using backslashes in a python string. However backslashes in a python string carry a special meaning and need to be escaped. See also here.

Possible solutions (supposing the file really exists):

  1. Escape backslashes

    img = cv2.imread('C:\\Documents\\data128.jpg',0)
    
  2. Use a raw string

    img = cv2.imread(r'C:\Documents\data128.jpg',0)
    
  3. Use single slashes

    img = cv2.imread('C:/Documents/data128.jpg',0)
    
Community
  • 1
  • 1
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712