-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdft_viewer.py
More file actions
73 lines (56 loc) · 1.93 KB
/
dft_viewer.py
File metadata and controls
73 lines (56 loc) · 1.93 KB
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
import cv2
import numpy as np
def compute_dft(gray: np.ndarray) -> np.ndarray:
"""Compute magnitude spectrum of grayscale image using DFT."""
float_gray = np.float32(gray)
dft = cv2.dft(float_gray, flags=cv2.DFT_COMPLEX_OUTPUT)
dft_shift = np.fft.fftshift(dft)
magnitude = cv2.magnitude(dft_shift[:, :, 0], dft_shift[:, :, 1])
magnitude += 1e-8 # avoid log(0)
magnitude_log = np.log(magnitude)
magnitude_norm = cv2.normalize(magnitude_log, None, 0, 255, cv2.NORM_MINMAX)
return magnitude_norm.astype(np.uint8)
def main():
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Error: Could not open webcam")
return
print("Webcam opened successfully!")
print("Press 'q' to quit")
while True:
ret, frame = cap.read()
if not ret:
print("Error: Could not read frame")
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
spectrum = compute_dft(gray)
# Convert to BGR to stack with original
spectrum_bgr = cv2.cvtColor(spectrum, cv2.COLOR_GRAY2BGR)
gray_bgr = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
combined = np.hstack((frame, gray_bgr, spectrum_bgr))
cv2.putText(combined, "Original", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
cv2.putText(
combined,
"Grayscale",
(frame.shape[1] + 10, 30),
cv2.FONT_HERSHEY_SIMPLEX,
0.7,
(0, 255, 0),
2,
)
cv2.putText(
combined,
"DFT Magnitude Spectrum",
(frame.shape[1] * 2 + 10, 30),
cv2.FONT_HERSHEY_SIMPLEX,
0.7,
(0, 255, 0),
2,
)
cv2.imshow("Discrete Fourier Transform Viewer", combined)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()