import sys import numpy as np import cv2 as cv import argparse from aruco_types import ARUCO_DICT def factory(dict_type: int, square_length: float=200.0, marker_length: float=120.0, margin_length=10): aruco_dict = cv.aruco.getPredefinedDictionary(dict_type) board = cv.aruco.CharucoBoard((3,3), square_length, marker_length, aruco_dict) params = cv.aruco.CharucoParameters() detector = cv.aruco.CharucoDetector(board, params) side_len = int(3.0*square_length + 2.0*margin_length) image = board.generateImage((side_len, side_len), None, margin_length, 1) cv.imwrite("results/charuco_diamond_board.png", image) return detector, board def main(): # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-t", "--type", type=str, default="DICT_ARUCO_ORIGINAL", help="type of ArUCo tag to detect") args = vars(ap.parse_args()) # verify that the supplied ArUCo tag exists and is supported by # OpenCV if ARUCO_DICT.get(args["type"], None) is None: print("[INFO] ArUCo tag of '{}' is not supported".format( args["type"])) sys.exit(0) # load the ArUCo dictionary, grab the ArUCo parameters, and detect # the markers print("[INFO] detecting '{}' tags...".format(args["type"])) detector, board = factory(ARUCO_DICT[args["type"]]) # load the input image from disk and resize it print("[INFO] start processing...") process_video(detector, board) def process_video(detector: cv.aruco.CharucoDetector, board): with np.load('results/cam.npz') as X: mtx, dist, _, _ = [X[i] for i in ('mtx', 'dist', 'rvecs', 'tvecs')] # Open camera video = cv.VideoCapture(0) if not video.isOpened(): print("Cannot open camera") exit() while True: # Read a new frame ok, img = video.read() if not ok: return process(detector, board, img, mtx, dist) k = cv.waitKey(1) & 0xFF if k == ord('q'): break def process(detector: cv.aruco.CharucoDetector, board: cv.aruco.Board, img, mtx, dist): # Load previously saved data gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) diamond_corners, diamond_ids, marker_corners, marker_ids = detector.detectDiamonds(gray) if diamond_corners is not None: # Draw a square around the markers cv.aruco.drawDetectedCornersCharuco(img, diamond_corners, diamond_ids) # Draw a square around the markers cv.aruco.drawDetectedMarkers(img, marker_corners) if len(diamond_ids) >= len(board.getIds()): # Draw a square around the markers cv.aruco.drawDetectedDiamonds(img, diamond_corners, diamond_ids) if False and diamond_ids is not None and len(diamond_ids) > 0: obj_points, img_points = board.matchImagePoints(diamond_corners, diamond_ids) pose, rvec, tvec = cv.solvePnP(obj_points, img_points, mtx, dist, None, None) if pose: # Draw Axis cv.drawFrameAxes(img, mtx, dist, rvec, tvec, 10) cv.imshow('img', img) if __name__ == '__main__': main() cv.destroyAllWindows()