1import cv2
2import numpy as np
3from scipy import signal
4
5
6def processImage(frame):
7 # Turn image into float32
8 frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
9 frame = np.float32(frame / 255.0)
10
11 # Calculate Gradient in X and Y, scale appropiately
12 gx = cv2.Sobel(frame, cv2.CV_32F, 1, 0, ksize=3) / 4.0
13 gy = cv2.Sobel(frame, cv2.CV_32F, 0, 1, ksize=3) / 4.0
14
15 # Calculate Ix^2, IxIy and Iy^2 images
16 Ix2, IxIy, Iy2 = gx**2, gx * gy, gy**2
17
18 # Apply Block filter for summation, divide by size of kernel for normalization
19 N = 7
20 Ix2 = signal.convolve2d(Ix2, np.ones((N, N))) / (N**2)
21 Iy2 = signal.convolve2d(Iy2, np.ones((N, N))) / (N**2)
22 IxIy = signal.convolve2d(IxIy, np.ones((N, N))) / (N**2)
23
24 # Harris Corner Strength
25 kappa = 0.04
26 det = Ix2 * Iy2 - IxIy**2
27 trace = Ix2 + Iy2
28 strength = det - kappa * trace**2
29
30 strength /= np.max(strength)
31
32 corners = np.zeros_like(strength)
33 corners[strength > 0.1] = 1.0
34
35 cv2.imshow("Harris Corner Strength", strength)
36 cv2.imshow("Harris Corners", corners)
37
38
39def mainLoop():
40 """
41 The main loop of this program
42 """
43 # TODO: Open the default camera
44 cam = cv2.VideoCapture(0)
45
46 while True:
47 # TODO: Read next image from camera
48 _, frame = cam.read()
49
50 # TODO: Call processImage to retrieve properly scaled gradient direction and magnitude images
51 processImage(frame)
52
53 # TODO: Also display the original camera image in color
54 cv2.imshow("Camera", frame)
55
56 # TODO: Break the infinite loop when the users presses ESCAPE (27)
57 if cv2.waitKey(1) == 27:
58 break
59
60 # TODO: Release the capture and writer objects
61 cam.release()
62 cv2.destroyAllWindows()
63
64
65if __name__ == "__main__":
66 mainLoop()