-
Notifications
You must be signed in to change notification settings - Fork 0
/
dft.py
75 lines (55 loc) · 2.08 KB
/
dft.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import cv2
import math
import numpy as np
from math import pi
from matplotlib import pyplot as plt
from PIL import Image
def run(in_file, out_file):
img = cv2.imread(in_file)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
rows, cols = gray.shape
dft = cv2.dft(np.float32(gray),flags = cv2.DFT_COMPLEX_OUTPUT)
dft_shift = np.fft.fftshift(dft)
magnitude_spectrum = 20*np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1]))
(_, thresh) = cv2.threshold(magnitude_spectrum, 230, 255, cv2.THRESH_BINARY)
thresh = np.uint8(thresh)
lines = cv2.HoughLines(thresh,1,np.pi/180,30)
magnitude_spectrum_lines = np.copy(magnitude_spectrum)
for rho,theta in lines[0]:
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*(a))
m_numerator = y2 - y1
m_denominator = x2 - x1
angle = np.rad2deg(math.atan2(m_numerator, m_denominator))
M = cv2.getRotationMatrix2D((cols/2, rows/2), angle, 1)
if cols > rows:
out_dims = (cols, cols)
else:
out_dims = (rows, rows)
rotated_img = cv2.warpAffine(img, M, out_dims)
cv2.line(magnitude_spectrum_lines,(x1,y1),(x2,y2),(0,0,255),2)
b,g,r = cv2.split(rotated_img)
rotated_img = cv2.merge([r,g,b])
rotated_img = Image.fromarray(rotated_img)
rotated_img.save(out_file)
magnitude_spectrum = Image.fromarray(magnitude_spectrum).convert('RGB')
magnitude_spectrum.save('results/fourier.png')
magnitude_spectrum_lines = Image.fromarray(magnitude_spectrum_lines).convert('RGB')
magnitude_spectrum_lines.save('results/fourier_lines.png')
"""
plt.subplot(141),plt.imshow(gray, cmap = 'gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(142),plt.imshow(thresh, cmap = 'gray')
plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
plt.subplot(143),plt.imshow(magnitude_spectrum_lines, cmap = 'gray')
plt.title('Magnitude spectrum lines'), plt.xticks([]), plt.yticks([])
plt.subplot(144),plt.imshow(rotated_img, cmap = 'gray')
plt.title('Image corrected'), plt.xticks([]), plt.yticks([])
plt.show()
"""