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.
Before you start
Section titled “Before you start”- 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
pypucliband 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.
- Make sure the C++ version of Finding moving objects works. This program uses the same “run the analysis on several threads” structure.
- Install OpenCV following Setting up OpenCV (C++). The features for ArUco markers are built into OpenCV 4.7 and later.
- The program in the sample code bundle has Japanese comments. The code below is the same program with English comments and messages.
What you need
Section titled “What you need”| 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 |
Try it
Section titled “Try it”-
Enter and save the program
Save the following code as
aruco_tracking.pyinC:\infinicam_projects\python\applications(create theapplicationsfolder if it does not exist).import mathimport queueimport sysimport threadingimport timeimport cv2from pypuclib import CameraFactory, Decoder, PUCExceptionFRAMERATE = 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 timeDECODE_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 exitif 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 fasterparams.adaptiveThreshWinSizeMin = 7params.adaptiveThreshWinSizeMax = 7params.adaptiveThreshWinSizeStep = 10return cv2.aruco.ArucoDetector(dictionary, params)print("Connecting to the camera...")try:# Connect to the GbE-2 at this IP addresscam = 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 = Nonenext_frame_no = 0# For display: the newest image and the markers foundshown = {"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_nostats["received"] += 1# If the sequence number skips, the skipped frames were droppedseq = xfer.sequenceNo()if last_seq is not None:stats["gaps"] += ((seq - last_seq) & 0xFFFF) - 1last_seq = seqif xfer.isDamaged():returntry:frames.put_nowait((next_frame_no, xfer.data().copy()))next_frame_no += 1except queue.Full:stats["overflow"] += 1 # Analysis could not keep up and the queue overfloweddef 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 searchingsmall = 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 imagecx, cy = points.mean(axis=0) # The center is the average of the 4 cornersdx, dy = points[1] - points[0] # Direction from the top-left corner to the top-right cornerangle = math.degrees(math.atan2(dy, dx)) # Rotation angle of the marker [degrees]markers.append((int(marker_id), points, cx, cy, angle))return markersdef 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 finishbreakframe_no, data = itemstart = time.perf_counter()image = decoder.decode(data, reso)markers = find_markers(detector, image)elapsed = time.perf_counter() - startwith lock:stats["processed"] += 1stats["process_time"] += elapsed# Only once every SHOW_EVERY frames, hand over the image and results for displayif frame_no % SHOW_EVERY == 0:shown["image"] = imageshown["markers"] = markerswindow = "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 = 0last_process_time = 0.0info = ""while True:with lock:image = shown["image"]markers = shown["markers"]shown["image"] = Noneprocessed = stats["processed"]process_time = stats["process_time"]# Every second, work out how many frames were analyzed in the last second and the time per framenow = time.perf_counter()if now - last_time >= 1.0:n = processed - last_processedper_frame = (process_time - last_process_time) / n * 1000 if n else 0info = (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_timeif image is not None:if image.ndim == 2:image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) # Convert to color so the lines can be coloredcv2.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 outlinecv2.circle(image, (int(cx), int(cy)), 4, (0, 0, 255), -1) # Centercv2.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) & 0xFFif key in (27, ord("q"), ord("Q")): # ESC or Qbreakfinally:# Stop continuous transfer, let all analysis workers finish, then close the cameracam.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']}).") -
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\applicationsTerminal window python aruco_tracking.py --make-markersMarker images for IDs 0 to 3 (
aruco_marker_0.pngtoaruco_marker_3.png) are created in the same folder. Print one of them (or all of them).Saved: aruco_marker_0.pngSaved: aruco_marker_1.pngSaved: aruco_marker_2.pngSaved: aruco_marker_3.png -
Run it
Run the following line (without
--make-markers, marker tracking starts).Terminal window python aruco_tracking.py -
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: 0ID 0: x=412 y=298 angle=15 deg -
Exit
Select the video window and press
ESCorQ.Done (received: 8000, analyzed: 8000, dropped: 0, overflow: 0).If “received” and “analyzed” are the same, every frame was analyzed without skipping any.
-
Create and set up the project
- Create a new project the same way as steps 1 to 7 of Creating the HelloWorld Project. Save it in
C:\infinicam_projects\applicationsand name the projectArucoTracking. - Following step 3 of Setting up OpenCV (C++), add the OpenCV settings (include, library, and automatic DLL copy) to this project.
- Create a new project the same way as steps 1 to 7 of Creating the HelloWorld Project. Save it in
-
Write the source code
Open the main file (
ArucoTracking.cpp) and replace its contents with the following code.#include <stdio.h>#include <stdlib.h>#include <string.h>#include <math.h>#include <algorithm>#include <condition_variable>#include <deque>#include <mutex>#include <thread>#include <vector>#include <windows.h>#include <PUCLIB.h> // PUCLIB header#include <opencv2/opencv.hpp> // OpenCV header (ArUco is also included from here)#include <opencv2/core/utils/logger.hpp> // For setting which messages OpenCV printsconst UINT32 FRAMERATE = 1000; // Frame rate [fps]const int SHOW_EVERY = 33; // Hand over an image for display once every this many frames (33 frames = about 30 fps)const int WORKERS = 3; // Number of analysis workers (threads). They process different frames at the same timeconst int DECODE_THREADS = 4; // Number of threads used to decode one frame (per worker)const int SLOTS = 256; // Number of places to keep received compressed data// The kind of marker used (4 x 4 squares, IDs 0-49)const cv::aruco::PredefinedDictionaryType MARKER_TYPE = cv::aruco::DICT_4X4_50;// Information about one marker foundstruct Marker {int id;cv::Point2f corners[4]; // Top-left, top-right, bottom-right, and bottom-left cornerscv::Point2f center;double angle; // Rotation angle [degrees] (clockwise is positive)};// Data shared between threadsstruct ArucoContext {UINT32 width;UINT32 height;UINT32 lineBytes;unsigned short qVals[PUC_Q_COUNT];// Places for received compressed data, and the queue of frame numbers waiting to be analyzedstd::vector<std::vector<unsigned char>> slots;std::deque<long> waiting;std::mutex queueLock;std::condition_variable queueReady;bool stopping;// Counters (protected by statsLock)std::mutex statsLock;long nextFrameNo; // Number given to received frames, counting up from 0long received;long processed;long gaps;long overflow;int lastSeq;double processSeconds;// For display: the newest image and the markers found (protected by statsLock)cv::Mat shownImage;std::vector<Marker> shownMarkers;bool isUpdated;};static double NowSeconds() {static LARGE_INTEGER freq = [] { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return f; }();LARGE_INTEGER t;QueryPerformanceCounter(&t);return (double)t.QuadPart / freq.QuadPart;}// Make marker images for printing (IDs 0-3)static void MakeMarkers() {cv::aruco::Dictionary dictionary = cv::aruco::getPredefinedDictionary(MARKER_TYPE);for (int id = 0; id < 4; id++) {cv::Mat image;cv::aruco::generateImageMarker(dictionary, id, 400, image);// Add a white margin around it (without a margin, detection may fail)cv::copyMakeBorder(image, image, 50, 50, 50, 50, cv::BORDER_CONSTANT, cv::Scalar(255));char filename[64];sprintf_s(filename, "aruco_marker_%d.png", id);cv::imwrite(filename, image);printf("Saved: %s\n", filename);}}// Make a marker detector (each worker uses its own detector)static cv::aruco::ArucoDetector MakeDetector() {cv::aruco::DetectorParameters params;// Use only one window size for thresholding (splitting into black and white) to make detection fasterparams.adaptiveThreshWinSizeMin = 7;params.adaptiveThreshWinSizeMax = 7;params.adaptiveThreshWinSizeStep = 10;return cv::aruco::ArucoDetector(cv::aruco::getPredefinedDictionary(MARKER_TYPE), params);}// Find markers in the imagestatic void FindMarkers(cv::aruco::ArucoDetector& detector, const cv::Mat& image, std::vector<Marker>& markers) {std::vector<std::vector<cv::Point2f>> corners;std::vector<int> ids;detector.detectMarkers(image, corners, ids);for (size_t i = 0; i < ids.size(); i++) {Marker m;m.id = ids[i];m.center = cv::Point2f(0, 0);for (int k = 0; k < 4; k++) {m.corners[k] = corners[i][k];m.center += corners[i][k] * 0.25f; // The center is the average of the 4 corners}cv::Point2f top = m.corners[1] - m.corners[0]; // Direction from the top-left corner to the top-right cornerm.angle = atan2(top.y, top.x) * 180.0 / CV_PI;markers.push_back(m);}}// Callback function called automatically from inside the SDK every time an image arrives.// Do nothing heavy here: just copy the compressed data to a slot and put it in the queuevoid WINAPI ImageCallback(PPUC_XFER_DATA_INFO pXferData, void* pUserParam) {ArucoContext* c = (ArucoContext*)pUserParam;if (!pXferData || !pXferData->pData || !c) {return;}long frameNo = -1;{std::lock_guard<std::mutex> guard(c->statsLock);c->received++;// If the sequence number skips, the skipped frames were droppedint seq = pXferData->nSequenceNo;if (c->lastSeq >= 0) {c->gaps += ((seq - c->lastSeq) & 0xFFFF) - 1;}c->lastSeq = seq;if (pXferData->isDamaged) {return; // Skip data that arrived incomplete}frameNo = c->nextFrameNo++;}{std::lock_guard<std::mutex> guard(c->queueLock);if ((int)c->waiting.size() >= SLOTS - WORKERS) {std::lock_guard<std::mutex> statsGuard(c->statsLock);c->overflow++; // Analysis could not keep up and the slots are fullreturn;}std::vector<unsigned char>& slot = c->slots[frameNo % SLOTS];memcpy(slot.data(), pXferData->pData, std::min((size_t)pXferData->nDataSize, slot.size()));c->waiting.push_back(frameNo);}c->queueReady.notify_one();}// Analysis worker (runs in a separate thread). Takes frames out of the queue one by one, decodes them, and finds markersstatic void AnalyzeWorker(ArucoContext* c) {cv::aruco::ArucoDetector detector = MakeDetector();// This worker's place for the decoded image (an image whose rows are lineBytes bytes long)cv::Mat buffer((int)c->height, (int)c->lineBytes, CV_8UC1);cv::Mat image = buffer(cv::Rect(0, 0, (int)c->width, (int)c->height));while (true) {long frameNo;{std::unique_lock<std::mutex> guard(c->queueLock);c->queueReady.wait(guard, [c] { return c->stopping || !c->waiting.empty(); });if (c->waiting.empty()) {return; // Signal to finish}frameNo = c->waiting.front();c->waiting.pop_front();}double start = NowSeconds();// Decode the full frame and find markersPUC_DecodeDataMultiThread(image.data, 0, 0, c->width, c->height, c->lineBytes,c->slots[frameNo % SLOTS].data(), c->qVals, DECODE_THREADS);std::vector<Marker> markers;FindMarkers(detector, image, markers);double elapsed = NowSeconds() - start;std::lock_guard<std::mutex> guard(c->statsLock);c->processed++;c->processSeconds += elapsed;// Only once every SHOW_EVERY frames, hand over the image and results for displayif (frameNo % SHOW_EVERY == 0) {image.copyTo(c->shownImage);c->shownMarkers = markers;c->isUpdated = true;}}}int main(int argc, char* argv[]) {// Stop the notices (INFO) that OpenCV prints, and show only warnings and errorscv::utils::logging::setLogLevel(cv::utils::logging::LOG_LEVEL_WARNING);// When run as "ArucoTracking.exe --make-markers", make the marker images and exitif (argc > 1 && strcmp(argv[1], "--make-markers") == 0) {MakeMarkers();return EXIT_SUCCESS;}printf("INFINICAM GbE-2 ArUco marker tracking (C++) starting...\n");// 1. Initialize the SDKPUCRESULT ret = PUC_Initialize();if (ret != PUC_SUCCEEDED) {printf("Error: failed to initialize the SDK. ErrorCode: %d\n", ret);return EXIT_FAILURE;}// 2. Search for GbE-2 cameras on the networkPUC_DETECT_FILTER filter = { 0 };filter.nDeviceTypeFlags = PUC_DETECT_TARGET_GBE2;PUC_DETECT_INFO detectInfo = { 0 };ret = PUC_DetectDevice2(&filter, &detectInfo);if (ret != PUC_SUCCEEDED || detectInfo.nDeviceCount == 0) {printf("Error: no GbE-2 camera was found. ErrorCode: %d\n", ret);return EXIT_FAILURE;}// 3. Open the first camera foundPUC_HANDLE hDevice = NULL;ret = PUC_OpenDevice2(0, &hDevice);if (ret != PUC_SUCCEEDED) {printf("Error: could not open the camera. ErrorCode: %d\n", ret);return EXIT_FAILURE;}// 4. Set the frame rate and shutter speed (set here because the camera may still have the settings from its last use)ret = PUC_SetFramerateShutter(hDevice, FRAMERATE, FRAMERATE);if (ret != PUC_SUCCEEDED) {printf("Error: failed to set the frame rate. ErrorCode: %d\n", ret);PUC_CloseDevice(hDevice);return EXIT_FAILURE;}// 5. Get the resolution, the quantization table, and the size of one frame of compressed dataArucoContext ctx;PUC_GetResolution(hDevice, &ctx.width, &ctx.height);PUC_GetQuantization2(hDevice, ctx.qVals);UINT32 xferDataSize = 0;PUC_GetXferDataSize(hDevice, &xferDataSize);ctx.lineBytes = (ctx.width + 3) & ~3; // Align to a 4-byte boundaryprintf("Capture settings: %u x %u pixels, %u fps\n", ctx.width, ctx.height, FRAMERATE);// 6. Prepare the places for compressed datactx.slots.assign(SLOTS, std::vector<unsigned char>(xferDataSize));ctx.stopping = false;ctx.nextFrameNo = 0;ctx.received = 0;ctx.processed = 0;ctx.gaps = 0;ctx.overflow = 0;ctx.lastSeq = -1;ctx.processSeconds = 0.0;ctx.isUpdated = false;// 7. Start the analysis workers (threads)std::vector<std::thread> workers;for (int i = 0; i < WORKERS; i++) {workers.emplace_back(AnalyzeWorker, &ctx);}const char* windowName = "ArUco tracking (ESC or Q to quit)";cv::namedWindow(windowName, cv::WINDOW_AUTOSIZE);// 8. Start continuous transferPUC_SetRingBufferCount(hDevice, 64);ret = PUC_BeginXferData(hDevice, ImageCallback, &ctx);if (ret != PUC_SUCCEEDED) {printf("Error: failed to start continuous transfer. ErrorCode: %d\n", ret);PUC_CloseDevice(hDevice);return EXIT_FAILURE;}printf("Tracking markers... Select the video window and press ESC or Q to exit.\n");// 9. Main loop: show the results and watch for key pressesdouble lastTime = NowSeconds();long lastProcessed = 0;double lastProcessSeconds = 0.0;char info[160] = "";cv::Mat image;std::vector<Marker> markers;while (true) {bool updated = false;long processed, gaps, overflow;double processSeconds;{std::lock_guard<std::mutex> guard(ctx.statsLock);if (ctx.isUpdated) {ctx.isUpdated = false;ctx.shownImage.copyTo(image);markers = ctx.shownMarkers;updated = true;}processed = ctx.processed;gaps = ctx.gaps;overflow = ctx.overflow;processSeconds = ctx.processSeconds;}// Every second, work out how many frames were analyzed in the last second and the time per framedouble now = NowSeconds();if (now - lastTime >= 1.0) {long n = processed - lastProcessed;double perFrame = n > 0 ? (processSeconds - lastProcessSeconds) / n * 1000.0 : 0.0;sprintf_s(info, "process: %.0f fps (%.2f ms/frame, %d workers) dropped: %ld overflow: %ld",n / (now - lastTime), perFrame, WORKERS, gaps, overflow);lastTime = now;lastProcessed = processed;lastProcessSeconds = processSeconds;}if (updated) {cv::Mat color;cv::cvtColor(image, color, cv::COLOR_GRAY2BGR); // Convert to color so the lines can be coloredcv::putText(color, info, cv::Point(10, 25), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 2);for (size_t i = 0; i < markers.size(); i++) {const Marker& m = markers[i];for (int k = 0; k < 4; k++) { // Marker outlinecv::line(color, m.corners[k], m.corners[(k + 1) % 4], cv::Scalar(0, 0, 255), 2);}cv::circle(color, m.center, 4, cv::Scalar(0, 0, 255), -1); // Centerchar label[32];sprintf_s(label, "ID %d", m.id);cv::putText(color, label, m.corners[0] + cv::Point2f(0, -8),cv::FONT_HERSHEY_SIMPLEX, 0.6, cv::Scalar(0, 0, 255), 2);char text[96];sprintf_s(text, "ID %d: x=%.0f y=%.0f angle=%.0f deg", m.id, m.center.x, m.center.y, m.angle);cv::putText(color, text, cv::Point(10, 50 + 22 * (int)i),cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 2);}cv::imshow(windowName, color);}int key = cv::waitKey(1);if (key == 27 || key == 'q' || key == 'Q') { // ESC or Qbreak;}}// 10. Clean up: stop continuous transfer, let the analysis workers finish, then close the cameraPUC_EndXferData(hDevice);{std::lock_guard<std::mutex> guard(ctx.queueLock);ctx.stopping = true;}ctx.queueReady.notify_all();for (auto& worker : workers) {worker.join();}cv::destroyAllWindows();printf("Done (received: %ld, analyzed: %ld, dropped: %ld, overflow: %ld).\n",ctx.received, ctx.processed, ctx.gaps, ctx.overflow);PUC_CloseDevice(hDevice);return EXIT_SUCCESS;} -
Set the configuration to “Release” and build
In the toolbar at the top of the window, switch the configuration from
DebugtoRelease, then build with Build > Build Solution (Ctrl+Shift+B) from the menu. -
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\applications\ArucoTracking\x64\ReleaseTerminal window ArucoTracking.exe --make-markersMarker images for IDs 0 to 3 (
aruco_marker_0.pngtoaruco_marker_3.png) are created in the same folder. Print one of them (or all of them). They are the same as the images made by the Python version, so you can make them with either. -
Run it
Go back to Visual Studio and press
Ctrl+F5. 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.30 ms/frame, 3 workers) dropped: 0 overflow: 0ID 0: x=412 y=298 angle=15 deg -
Exit
Select the video window and press
ESCorQ. The console window shows the following.Done (received: 8000, analyzed: 8000, dropped: 0, overflow: 0).
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) |
How the program works
Section titled “How the program works”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) / SCALESearching 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 = 7params.adaptiveThreshWinSizeMax = 7params.adaptiveThreshWinSizeStep = 10To 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).
1. Process different frames at the same time with 3 workers
As in the C++ version of Finding moving objects, the receiving side only copies the compressed data to a slot, and WORKERS (3) analysis workers (threads) do the rest.
Motion detection needed “the image from 10 frames earlier”, but marker detection can be done on each frame independently. So there is no need to keep decoded images; each worker only needs one working image (buffer) of its own. Each worker also makes its own marker detector (cv::aruco::ArucoDetector).
2. Search the full frame for markers
The detection time per frame, measured without the camera (a guide; Release, an image containing one marker), was as follows.
| Image searched | Default settings | One thresholding window size |
|---|---|---|
| 800 x 600 (full frame) | About 1.2 ms | About 0.7 ms |
| 400 x 300 (half size) | About 0.6 ms | About 0.4 ms |
The C++ version gives priority to precise positions and searches the full frame. Together with decoding (about 0.6 ms) it takes about 1.3 ms per frame, but shared among 3 workers that works out to more than 2,000 frames per second.
3. Settings that make detection faster
params.adaptiveThreshWinSizeMin = 7;params.adaptiveThreshWinSizeMax = 7;params.adaptiveThreshWinSizeStep = 10;Using only one thresholding window size makes detection faster. The idea is the same as the Python version.
4. Center position and rotation angle
m.center += corners[i][k] * 0.25f; // The center is the average of the 4 cornerscv::Point2f top = m.corners[1] - m.corners[0]; // Direction from the top-left corner to the top-right cornerm.angle = atan2(top.y, top.x) * 180.0 / CV_PI;The calculation is the same as the Python version. The angle is positive clockwise.
Things to try
Section titled “Things to try”| 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) |
| Change | Example | What happens |
|---|---|---|
WORKERS = 3 |
1 |
With only one worker, it no longer keeps up with 1,000 fps (check that overflow goes up) |
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 |
PUC_SetFramerateShutter(hDevice, FRAMERATE, FRAMERATE) |
PUC_SetFramerateShutter(hDevice, FRAMERATE, 4000) |
The shutter speed becomes 1/4000 s, so the pattern blurs less even when moved fast (the image becomes darker) |
Troubleshooting
Section titled “Troubleshooting”| 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++) |
Ideas for going further
Section titled “Ideas for going further”- 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::solvePnPcan 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.
