You can use the cv2.aruco.detectMarkers() function to detect the markers in an image:
corners, ids, rejected_corners = cv2.aruco.detectMarkers(gray_frame, aruco_dictionary, parameters=parameters)
The first parameter of cv2.aruco.detectMarkers() is the grayscale image where the markers are going to be detected. The second parameter is the dictionary object, which should have been previously created. The third parameter establishes all of the parameters that can be customized during the detection process. This function returns the following information:
- The list of corners of the detected markers is returned. For each marker, its four corners (top-left, top-right, bottom-right, and bottom-left) are returned.
- The list of the identifiers of the detected markers is returned.
- The list of rejected candidates is returned, which is composed of all of the squares that have been found, but they do not have a proper codification. This list of rejected candidates is useful for debugging purposes. Each rejected candidate is composed of its four corners.
The aruco_detect_markers.py script detects markers from the webcam. First, the markers are detected using the aforementioned cv2.aruco.detectMarkers() function and, then, we will draw both the detected markers and the rejected candidates using cv2.aruco.drawDetectedMarkers() function, as follows:
# Draw detected markers:
frame = cv2.aruco.drawDetectedMarkers(image=frame, corners=corners, ids=ids, borderColor=(0, 255, 0))
# Draw rejected markers:
frame = cv2.aruco.drawDetectedMarkers(image=frame, corners=rejected_corners, borderColor=(0, 0, 255))
If you execute the aruco_detect_markers.py script, detected markers will be drawn with a green border, while the rejected candidates will be drawn with a red border, as shown in the following screenshot:
In the preceding screenshot, you can see that a marker (with id=2) is detected, which is drawn with a green border. Additionally, you can also see two rejected candidates with a red border.