Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/python/dft.py
16337 views
1
#!/usr/bin/env python
2
3
'''
4
sample for disctrete fourier transform (dft)
5
6
USAGE:
7
dft.py <image_file>
8
'''
9
10
11
# Python 2/3 compatibility
12
from __future__ import print_function
13
14
import cv2 as cv
15
import numpy as np
16
import sys
17
18
19
def shift_dft(src, dst=None):
20
'''
21
Rearrange the quadrants of Fourier image so that the origin is at
22
the image center. Swaps quadrant 1 with 3, and 2 with 4.
23
24
src and dst arrays must be equal size & type
25
'''
26
27
if dst is None:
28
dst = np.empty(src.shape, src.dtype)
29
elif src.shape != dst.shape:
30
raise ValueError("src and dst must have equal sizes")
31
elif src.dtype != dst.dtype:
32
raise TypeError("src and dst must have equal types")
33
34
if src is dst:
35
ret = np.empty(src.shape, src.dtype)
36
else:
37
ret = dst
38
39
h, w = src.shape[:2]
40
41
cx1 = cx2 = w/2
42
cy1 = cy2 = h/2
43
44
# if the size is odd, then adjust the bottom/right quadrants
45
if w % 2 != 0:
46
cx2 += 1
47
if h % 2 != 0:
48
cy2 += 1
49
50
# swap quadrants
51
52
# swap q1 and q3
53
ret[h-cy1:, w-cx1:] = src[0:cy1 , 0:cx1 ] # q1 -> q3
54
ret[0:cy2 , 0:cx2 ] = src[h-cy2:, w-cx2:] # q3 -> q1
55
56
# swap q2 and q4
57
ret[0:cy2 , w-cx2:] = src[h-cy2:, 0:cx2 ] # q2 -> q4
58
ret[h-cy1:, 0:cx1 ] = src[0:cy1 , w-cx1:] # q4 -> q2
59
60
if src is dst:
61
dst[:,:] = ret
62
63
return dst
64
65
if __name__ == "__main__":
66
67
if len(sys.argv) > 1:
68
im = cv.imread(sys.argv[1])
69
else:
70
im = cv.imread('../data/baboon.jpg')
71
print("usage : python dft.py <image_file>")
72
73
# convert to grayscale
74
im = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
75
h, w = im.shape[:2]
76
77
realInput = im.astype(np.float64)
78
79
# perform an optimally sized dft
80
dft_M = cv.getOptimalDFTSize(w)
81
dft_N = cv.getOptimalDFTSize(h)
82
83
# copy A to dft_A and pad dft_A with zeros
84
dft_A = np.zeros((dft_N, dft_M, 2), dtype=np.float64)
85
dft_A[:h, :w, 0] = realInput
86
87
# no need to pad bottom part of dft_A with zeros because of
88
# use of nonzeroRows parameter in cv.dft()
89
cv.dft(dft_A, dst=dft_A, nonzeroRows=h)
90
91
cv.imshow("win", im)
92
93
# Split fourier into real and imaginary parts
94
image_Re, image_Im = cv.split(dft_A)
95
96
# Compute the magnitude of the spectrum Mag = sqrt(Re^2 + Im^2)
97
magnitude = cv.sqrt(image_Re**2.0 + image_Im**2.0)
98
99
# Compute log(1 + Mag)
100
log_spectrum = cv.log(1.0 + magnitude)
101
102
# Rearrange the quadrants of Fourier image so that the origin is at
103
# the image center
104
shift_dft(log_spectrum, log_spectrum)
105
106
# normalize and display the results as rgb
107
cv.normalize(log_spectrum, log_spectrum, 0.0, 1.0, cv.NORM_MINMAX)
108
cv.imshow("magnitude", log_spectrum)
109
110
cv.waitKey(0)
111
cv.destroyAllWindows()
112
113