Skip to content
⚡ Developer documentation for INFINICAM, the real-time high-speed camera (UC-1.1 / GbE-2)

Tracking ArUco markers

The program finds printed ArUco markers in every 1,000 fps image from the INFINICAM GbE-2 and shows each marker’s outline, ID, center position, and rotation angle.

ArUco markers are landmarks made of black-and-white square patterns. Each pattern has its own number (ID), and their position and orientation can be found accurately in an image, so they are often used as landmarks for measuring the position of robots and objects.

The top-left corner of the screen shows the number of frames analyzed per second (fps), the analysis time per frame, and the number of dropped frames.

Python version C++ version
Image searched for markers Scaled down to half size (400 x 300) Full frame (800 x 600)
Processing time per frame (guide) Decoding about 0.6 ms + detection about 0.4 ms Decoding about 0.6 ms + detection about 0.7 ms
How it keeps up with 1,000 fps 3 analysis workers (threads) process 3 frames at the same time 3 analysis workers (threads) process 3 frames at the same time

The detection times in the table are guides measured without the camera, on an 800 x 600 image containing one marker. The actual times depend on what is in the picture and on the PC. The Python version in particular may not reach 1,000 fps on some PCs. Even then, the process number on the screen tells you how many frames were actually analyzed.

  • Make sure the Python version of Finding moving objects works. This program uses the same “separate the receiving side from the analysis side” structure.
  • The only libraries used are pypuclib and OpenCV (opencv-python). The features for ArUco markers are built into OpenCV.
  • The program in the sample code bundle has Japanese comments. The code below is the same program with English comments and messages.
Item Details
Camera INFINICAM GbE-2 (with a lens) and the PC it is connected to
Markers The images made in the steps below, printed on plain paper
Card or similar Something to stick the printed markers on to keep them flat
  1. Enter and save the program

    Save the following code as aruco_tracking.py in C:\infinicam_projects\python\applications (create the applications folder if it does not exist).

    import math
    import queue
    import sys
    import threading
    import time
    import cv2
    from pypuclib import CameraFactory, Decoder, PUCException
    FRAMERATE = 1000 # Frame rate [fps]
    SCALE = 0.5 # Scale of the image used for detection (0.5 = half size, 400 x 300)
    WORKERS = 3 # Number of analysis workers (threads). They process different frames at the same time
    DECODE_THREADS = 2 # Number of threads used to decode one frame (per worker)
    SHOW_EVERY = 33 # Hand over an image for display once every this many frames (33 frames = about 30 fps)
    # The kind of marker used (4 x 4 squares, IDs 0-49)
    dictionary = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50)
    def make_markers():
    """Make marker images for printing (IDs 0-3)"""
    for marker_id in range(4):
    image = cv2.aruco.generateImageMarker(dictionary, marker_id, 400)
    # Add a white margin around it (without a margin, detection may fail)
    image = cv2.copyMakeBorder(image, 50, 50, 50, 50, cv2.BORDER_CONSTANT, value=255)
    filename = f"aruco_marker_{marker_id}.png"
    cv2.imwrite(filename, image)
    print("Saved:", filename)
    # When run as "python aruco_tracking.py --make-markers", make the marker images and exit
    if len(sys.argv) > 1 and sys.argv[1] == "--make-markers":
    make_markers()
    raise SystemExit(0)
    def make_detector():
    """Make a marker detector (each worker uses its own detector)"""
    params = cv2.aruco.DetectorParameters()
    # Use only one window size for thresholding (splitting into black and white) to make detection faster
    params.adaptiveThreshWinSizeMin = 7
    params.adaptiveThreshWinSizeMax = 7
    params.adaptiveThreshWinSizeStep = 10
    return cv2.aruco.ArucoDetector(dictionary, params)
    print("Connecting to the camera...")
    try:
    # Connect to the GbE-2 at this IP address
    cam = CameraFactory().create(ip="192.168.0.10")
    except PUCException as e:
    print("Error: could not connect to the camera.", e)
    raise SystemExit(1)
    # Set the frame rate (set here because the camera may still have the settings from its last use)
    cam.setFramerateShutter(FRAMERATE, FRAMERATE)
    reso = cam.resolution()
    # Prepare one decoder per worker, and warm each one up by decoding one frame
    # (the first decode takes time to set up, which causes dropped frames)
    quantization = cam.decoder().quantization()
    data = cam.grab()
    decoders = []
    for _ in range(WORKERS):
    decoder = Decoder(quantization)
    decoder.setNumDecodeThread(DECODE_THREADS)
    decoder.decode(data)
    decoders.append(decoder)
    # Queue that hands received data over to the analysis side (up to 1000 frames = 1 second)
    frames = queue.Queue(maxsize=1000)
    # Counters (received, gaps, and overflow are changed only by the receiving side)
    stats = {"received": 0, "gaps": 0, "overflow": 0, "processed": 0, "process_time": 0.0}
    last_seq = None
    next_frame_no = 0
    # For display: the newest image and the markers found
    shown = {"image": None, "markers": []}
    lock = threading.Lock()
    def on_frame(xfer):
    """Called every time a frame arrives. Do nothing heavy here: just put it in the queue"""
    global last_seq, next_frame_no
    stats["received"] += 1
    # If the sequence number skips, the skipped frames were dropped
    seq = xfer.sequenceNo()
    if last_seq is not None:
    stats["gaps"] += ((seq - last_seq) & 0xFFFF) - 1
    last_seq = seq
    if xfer.isDamaged():
    return
    try:
    frames.put_nowait((next_frame_no, xfer.data().copy()))
    next_frame_no += 1
    except queue.Full:
    stats["overflow"] += 1 # Analysis could not keep up and the queue overflowed
    def find_markers(detector, image):
    """Find markers in the image and return a list of (ID, 4 corners, center x, center y, angle)"""
    if image.ndim == 3:
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # For color images, convert to grayscale before searching
    small = cv2.resize(image, None, fx=SCALE, fy=SCALE, interpolation=cv2.INTER_AREA)
    corners, ids, _ = detector.detectMarkers(small)
    markers = []
    if ids is not None:
    for corner, marker_id in zip(corners, ids.ravel()):
    points = corner.reshape(4, 2) / SCALE # Convert coordinates in the scaled image back to the original image
    cx, cy = points.mean(axis=0) # The center is the average of the 4 corners
    dx, dy = points[1] - points[0] # Direction from the top-left corner to the top-right corner
    angle = math.degrees(math.atan2(dy, dx)) # Rotation angle of the marker [degrees]
    markers.append((int(marker_id), points, cx, cy, angle))
    return markers
    def analyze_worker(decoder):
    """Takes frames out of the queue one by one and finds markers (WORKERS threads run this at the same time)"""
    detector = make_detector()
    while True:
    item = frames.get()
    if item is None: # Signal to finish
    break
    frame_no, data = item
    start = time.perf_counter()
    image = decoder.decode(data, reso)
    markers = find_markers(detector, image)
    elapsed = time.perf_counter() - start
    with lock:
    stats["processed"] += 1
    stats["process_time"] += elapsed
    # Only once every SHOW_EVERY frames, hand over the image and results for display
    if frame_no % SHOW_EVERY == 0:
    shown["image"] = image
    shown["markers"] = markers
    window = "ArUco tracking (ESC or Q to quit)"
    cv2.namedWindow(window, cv2.WINDOW_AUTOSIZE)
    workers = [threading.Thread(target=analyze_worker, args=(d,)) for d in decoders]
    for worker in workers:
    worker.start()
    # Start continuous transfer (on_frame is called every time a frame arrives)
    cam.setRingBufferCount(64)
    cam.beginXfer(on_frame)
    print("Tracking markers... Select the video window and press ESC or Q to exit.")
    try:
    last_time = time.perf_counter()
    last_processed = 0
    last_process_time = 0.0
    info = ""
    while True:
    with lock:
    image = shown["image"]
    markers = shown["markers"]
    shown["image"] = None
    processed = stats["processed"]
    process_time = stats["process_time"]
    # Every second, work out how many frames were analyzed in the last second and the time per frame
    now = time.perf_counter()
    if now - last_time >= 1.0:
    n = processed - last_processed
    per_frame = (process_time - last_process_time) / n * 1000 if n else 0
    info = (f"process: {n / (now - last_time):.0f} fps ({per_frame:.2f} ms/frame, {WORKERS} workers) "
    f"dropped: {stats['gaps']} overflow: {stats['overflow']}")
    last_time, last_processed, last_process_time = now, processed, process_time
    if image is not None:
    if image.ndim == 2:
    image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) # Convert to color so the lines can be colored
    cv2.putText(image, info, (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
    for i, (marker_id, points, cx, cy, angle) in enumerate(markers):
    cv2.polylines(image, [points.astype("int32")], True, (0, 0, 255), 2) # Marker outline
    cv2.circle(image, (int(cx), int(cy)), 4, (0, 0, 255), -1) # Center
    cv2.putText(image, f"ID {marker_id}", (int(points[0][0]), int(points[0][1]) - 8),
    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
    cv2.putText(image, f"ID {marker_id}: x={cx:.0f} y={cy:.0f} angle={angle:.0f} deg",
    (10, 50 + 22 * i), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
    cv2.imshow(window, image)
    key = cv2.waitKey(1) & 0xFF
    if key in (27, ord("q"), ord("Q")): # ESC or Q
    break
    finally:
    # Stop continuous transfer, let all analysis workers finish, then close the camera
    cam.endXfer()
    for _ in workers:
    frames.put(None)
    for worker in workers:
    worker.join()
    cam.close()
    cv2.destroyAllWindows()
    print(f"Done (received: {stats['received']}, analyzed: {stats['processed']}, "
    f"dropped: {stats['gaps']}, overflow: {stats['overflow']}).")
  2. Make and print the marker images

    Run the following 2 lines, one at a time, in Command Prompt (or PowerShell).

    Terminal window
    cd C:\infinicam_projects\python\applications
    Terminal window
    python aruco_tracking.py --make-markers

    Marker images for IDs 0 to 3 (aruco_marker_0.png to aruco_marker_3.png) are created in the same folder. Print one of them (or all of them).

    Saved: aruco_marker_0.png
    Saved: aruco_marker_1.png
    Saved: aruco_marker_2.png
    Saved: aruco_marker_3.png
  3. Run it

    Run the following line (without --make-markers, marker tracking starts).

    Terminal window
    python aruco_tracking.py
  4. Move the marker

    When the video window opens, move or turn the printed marker in front of the camera. The marker is outlined in red, and its ID and center point are shown. The top-left corner shows numbers like these (the numbers are an example).

    process: 1000 fps (1.05 ms/frame, 3 workers) dropped: 0 overflow: 0
    ID 0: x=412 y=298 angle=15 deg
  5. Exit

    Select the video window and press ESC or Q.

    Done (received: 8000, analyzed: 8000, dropped: 0, overflow: 0).

    If “received” and “analyzed” are the same, every frame was analyzed without skipping any.

The display means the following.

Display Meaning
process: 1000 fps Number of frames analyzed in one second. Since capture is at 1,000 fps, around 1000 means every frame is being analyzed
ms/frame Time taken to process one frame (decoding and marker detection). With 3 workers, it keeps up as long as this is under 3 ms
dropped Number of frames that did not arrive (dropped frames)
overflow Number of frames that overflowed the queue because analysis could not keep up
ID 0: x=… y=… angle=… The ID of a marker found, its center position (pixels), and its rotation angle (degrees, clockwise is positive)

1. Process different frames at the same time with 3 workers

decoder = Decoder(quantization)
...
workers = [threading.Thread(target=analyze_worker, args=(d,)) for d in decoders]

Marker detection can be done on each frame independently, regardless of the frames before and after it. So the program creates WORKERS (3) analysis workers (threads), and whichever worker is free takes the next frame from the queue. Each worker has its own decoder (Decoder). A decoder with the same settings can be made from the quantization table taken with cam.decoder().quantization().

Python has a rule that only one piece of Python code can run at a time (the GIL). However, pypuclib decoding and OpenCV marker detection run outside this rule, so adding threads really does make it faster. Measuring detection alone without the camera, one worker handled about 2,300 frames per second and three workers about 5,200 (a guide).

2. Search for markers in a scaled-down image

small = cv2.resize(image, None, fx=SCALE, fy=SCALE, interpolation=cv2.INTER_AREA)
corners, ids, _ = detector.detectMarkers(small)
...
points = corner.reshape(4, 2) / SCALE

Searching the full frame (800 x 600) for markers takes several ms per frame. So the program scales the image down to half size (400 x 300) before searching. The positions of the corners found are divided by SCALE (0.5) to convert them back to positions in the original image.

3. Settings that make detection faster

params.adaptiveThreshWinSizeMin = 7
params.adaptiveThreshWinSizeMax = 7
params.adaptiveThreshWinSizeStep = 10

To find markers, the image is first split into black and white (thresholding). To find markers even with uneven brightness, OpenCV normally redoes the thresholding many times with windows of different sizes. Here the program uses only one window size (7 pixels), so it is done once. In exchange, markers can be harder to find when the brightness across the screen is very uneven.

4. Center position and rotation angle

cx, cy = points.mean(axis=0)
dx, dy = points[1] - points[0]
angle = math.degrees(math.atan2(dy, dx))

The 4 corners of a marker always come back in the order “top-left, top-right, bottom-right, bottom-left” (determined by the orientation of the marker’s pattern). The average of the 4 corners is the center, and the direction from the top-left to the top-right corner is the rotation angle. In image coordinates, y increases downward, so the angle is positive clockwise.

5. Making the marker images

image = cv2.aruco.generateImageMarker(dictionary, marker_id, 400)
image = cv2.copyMakeBorder(image, 50, 50, 50, 50, cv2.BORDER_CONSTANT, value=255)

generateImageMarker turns the marker with the given ID into a 400 x 400 pixel image, and a white margin is added around it. The kind of marker used is DICT_4X4_50 (patterns of 4 x 4 squares, IDs 0 to 49).


Change Example What happens
SCALE = 0.5 1.0 Searches the full frame, so markers that appear small are also found and positions become more precise. In exchange, each frame takes longer and it no longer keeps up with 1,000 fps (watch process and overflow)
WORKERS = 3 1 With only one worker, it no longer keeps up with 1,000 fps
WORKERS = 3 4 Gives more headroom. Try it when your PC has spare CPU cores
The 3 adaptiveThreshWinSize… lines Delete all 3 lines Goes back to OpenCV’s default settings. More robust to uneven brightness, but detection is slower
cam.setFramerateShutter(FRAMERATE, FRAMERATE) cam.setFramerateShutter(FRAMERATE, 4000) The shutter speed becomes 1/4000 s, so the pattern blurs less even when moved fast (the image becomes darker)

Symptom Likely cause What to do
The marker is not found The marker appears small, it is out of focus, or the white margin was cut off Move it closer so each side appears at least 80 pixels long on screen. Adjust the focus. Print it with the margin
The marker is sometimes found and sometimes not Reflected light, uneven brightness, or bent paper Stick it on card to keep it flat. Change the direction of the lights. Go back to the default thresholding settings (see “Things to try”)
The marker is not found when moved fast The pattern is blurred Use a faster shutter speed (see “Things to try”)
process is below 1000, or overflow goes up The PC cannot keep up For the C++ version, check that it is built in Release. Close other applications. Increase WORKERS. For the Python version, check that SCALE is 0.5
dropped does not stay at 0 Network settings Check jumbo packets in PC operating environment and network settings
module 'cv2' has no attribute 'aruco' (Python) or 'aruco': is not a member of 'cv' (C++) OpenCV is too old For Python, update opencv-python. For C++, install OpenCV 5 following Setting up OpenCV (C++)

  • If you record the marker’s center every frame, you get its trajectory and speed every 1 ms.
  • If you calibrate the camera (measure the lens distortion and focal length), OpenCV’s cv2.solvePnP / cv::solvePnP can also give the marker’s 3D position and orientation.
  • Test results for tracking markers at 1,000 fps will be introduced under “ArUco marker 1000 fps tracking” (coming soon) in Capture & Verification Data.