Kantendetektion - Musterlösung

 1import cv2
 2import numpy as np
 3
 4
 5def processImage(frame):
 6    """
 7    Process the provided image (3-channel BGR) and calculate
 8    gradients in X and Y direction as well as the gradient magnitude.
 9
10    gx and gy shall contain the gradient direction image with values between -1 and +1
11    grad shall contain the gradient magnitude image with values between 0 and 1
12
13    :param frame: 3-channel BGR image (np.array)
14    :return: 3-tupel (gx, gy, grad) containing the gradient image in X and Y direction as well as the gradient magnitude image (1-channel np.float32 images each).
15    """
16    # TODO: Convert the image to grey using cv2.cvtColor
17    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
18
19    # TODO: Convert the image to np.float32 (divide by 255.0 first for normalization)
20    frame_gray = np.float32(frame_gray / 255.0)
21
22    # TODO: Calculate Gradients and normalize
23    gx = cv2.Sobel(frame_gray, cv2.CV_32F, 1, 0, ksize=3) / 4.0
24    gy = cv2.Sobel(frame_gray, cv2.CV_32F, 0, 1, ksize=3) / 4.0
25
26    # Calculate Gradient Magnitude and normalize
27    grad = np.sqrt(gx**2 + gy**2) / np.sqrt(2.0)
28
29    # Return 3-tupel with gradient images and gradient magnitude
30    return gx, gy, grad
31
32
33def displayImage(gx, gy, grad):
34    """
35    Apply appropriate scaling and display the provided images.
36
37    :param gx: Gradient image in X-Direction (np.float32 image with values between -1 and +1)
38    :param gy: Gradient image in Y-Direction (np.float32 image with values between -1 and +1)
39    :param grad: Gradient magnitude image (np.float32 image with values between 0 and 1)
40    """
41    # TODO: Display the gradient X and gradient Y image. Scale appropriately (values must be between 0 and 1)
42    cv2.imshow("Gradient X", (0.5 * gx + 0.5))
43    cv2.imshow("Gradient Y", (0.5 * gy + 0.5))
44
45    # TODO: Display the gradient magnitude image. Scale appropriately (e.g. multiply by 4 for more contrast)
46    cv2.imshow("Gradient Magnitude", 4.0 * grad)
47
48
49def mainLoop():
50    """
51    The main loop of this program
52    """
53    # TODO: Open the default camera
54    cam = cv2.VideoCapture(0)
55
56    while True:
57        # TODO: Read next image from camera
58        _, frame = cam.read()
59
60        # TODO: Call processImage to retrieve properly scaled gradient direction and magnitude images
61        gx, gy, grad = processImage(frame)
62
63        # TODO: Call displayImage to display the images
64        displayImage(gx, gy, grad)
65
66        # TODO: Also display the original camera image in color
67        cv2.imshow("Camera", frame)
68
69        # TODO: Break the infinite loop when the users presses ESCAPE (27)
70        if cv2.waitKey(1) == 27:
71            break
72
73    # TODO: Release the capture and writer objects
74    cam.release()
75    cv2.destroyAllWindows()
76
77
78if __name__ == "__main__":
79    mainLoop()