Skip to content

Instantly share code, notes, and snippets.

@catree
Last active July 5, 2019 14:07
Show Gist options
  • Save catree/dd901325a6bb8cc5d8bce12eba70a794 to your computer and use it in GitHub Desktop.
Save catree/dd901325a6bb8cc5d8bce12eba70a794 to your computer and use it in GitHub Desktop.
#include <opencv2/opencv.hpp>
#include <opencv2/aruco.hpp>
using namespace std;
using namespace cv;
static bool readDetectorParameters(const string& filename, Ptr<aruco::DetectorParameters>& params)
{
FileStorage fs(filename, FileStorage::READ);
if(!fs.isOpened())
return false;
fs["adaptiveThreshWinSizeMin"] >> params->adaptiveThreshWinSizeMin;
fs["adaptiveThreshWinSizeMax"] >> params->adaptiveThreshWinSizeMax;
fs["adaptiveThreshWinSizeStep"] >> params->adaptiveThreshWinSizeStep;
fs["adaptiveThreshConstant"] >> params->adaptiveThreshConstant;
fs["minMarkerPerimeterRate"] >> params->minMarkerPerimeterRate;
fs["maxMarkerPerimeterRate"] >> params->maxMarkerPerimeterRate;
fs["polygonalApproxAccuracyRate"] >> params->polygonalApproxAccuracyRate;
fs["minCornerDistanceRate"] >> params->minCornerDistanceRate;
fs["minDistanceToBorder"] >> params->minDistanceToBorder;
fs["minMarkerDistanceRate"] >> params->minMarkerDistanceRate;
fs["cornerRefinementMethod"] >> params->cornerRefinementMethod;
fs["cornerRefinementWinSize"] >> params->cornerRefinementWinSize;
fs["cornerRefinementMaxIterations"] >> params->cornerRefinementMaxIterations;
fs["cornerRefinementMinAccuracy"] >> params->cornerRefinementMinAccuracy;
fs["markerBorderBits"] >> params->markerBorderBits;
fs["perspectiveRemovePixelPerCell"] >> params->perspectiveRemovePixelPerCell;
fs["perspectiveRemoveIgnoredMarginPerCell"] >> params->perspectiveRemoveIgnoredMarginPerCell;
fs["maxErroneousBitsInBorderRate"] >> params->maxErroneousBitsInBorderRate;
fs["minOtsuStdDev"] >> params->minOtsuStdDev;
fs["errorCorrectionRate"] >> params->errorCorrectionRate;
fs["aprilTagQuadDecimate"] >> params->aprilTagQuadDecimate;
fs["aprilTagQuadSigma"] >> params->aprilTagQuadSigma;
fs["aprilTagMinClusterPixels"] >> params->aprilTagMinClusterPixels;
fs["aprilTagMaxNmaxima"] >> params->aprilTagMaxNmaxima;
fs["aprilTagMaxLineFitMse"] >> params->aprilTagMaxLineFitMse;
fs["aprilTagMinWhiteBlackDiff"] >> params->aprilTagMinWhiteBlackDiff;
fs["aprilTagDeglitch"] >> params->aprilTagDeglitch;
fs["detectInvertedMarker"] >> params->detectInvertedMarker;
return true;
}
int main(int argc, const char *argv[])
{
string input_filename = "";
int device = 0;
float quad_decimate = 1.0;
int nb_threads = 0;
string param_filename = "";
string save_directory = "";
bool show_rejected = false;
int corner_refine_method = aruco::CORNER_REFINE_APRILTAG;
bool verbose = false;
int tag_family = aruco::DICT_APRILTAG_36h11;
for (int i = 1; i < argc; i++) {
if (string(argv[i]) == "--input" && i+1 < argc) {
input_filename = string(argv[i+1]);
} else if (string(argv[i]) == "--device" && i+1 < argc) {
device = atoi(argv[i+1]);
} else if (string(argv[i]) == "--quad_decimate" && i+1 < argc) {
quad_decimate = (float)atof(argv[i+1]);
} else if (string(argv[i]) == "--nthreads" && i+1 < argc) {
nb_threads = atoi(argv[i+1]);
} else if (string(argv[i]) == "--save" && i+1 < argc) {
save_directory = string(argv[i+1]);
} else if (string(argv[i]) == "--param" && i+1 < argc) {
param_filename = string(argv[i+1]);
} else if (string(argv[i]) == "--rejected") {
show_rejected = true;
} else if (string(argv[i]) == "--corner_refine" && i+1 < argc) {
corner_refine_method = atoi(argv[i+1]);
} else if (string(argv[i]) == "--verbose") {
verbose = true;
} else if (string(argv[i]) == "--tag_family" && i+1 < argc) {
tag_family = atoi(argv[i+1]);
}
}
cout << "input_filename: " << input_filename << endl;
cout << "device: " << device << endl;
cout << "quad_decimate: " << quad_decimate << endl;
cout << "nb_threads: " << nb_threads << endl;
cout << "save_directory: " << save_directory << endl;
cout << "param_filename: " << param_filename << endl;
cout << "show_rejected: " << show_rejected << endl;
cout << "corner_refine_method: " << corner_refine_method << endl;
cout << "verbose: " << verbose << endl;
cout << "tag_family: " << tag_family << endl;
VideoCapture capture;
if (input_filename.empty()) {
capture.open(device);
} else {
capture.open(input_filename);
}
if (!capture.isOpened()) {
return 0;
}
Ptr<aruco::DetectorParameters> detectorParams = aruco::DetectorParameters::create();
if (!param_filename.empty()) {
readDetectorParameters(param_filename, detectorParams);
} else {
detectorParams->aprilTagQuadDecimate = quad_decimate;
detectorParams->cornerRefinementMethod = corner_refine_method;
if (nb_threads > 0) {
setNumThreads(nb_threads);
}
}
cout << "\ndetectorParams:" << endl;
cout << "adaptiveThreshWinSizeMin: " << detectorParams->adaptiveThreshWinSizeMin << endl;
cout << "adaptiveThreshWinSizeMax: " << detectorParams->adaptiveThreshWinSizeMax << endl;
cout << "adaptiveThreshWinSizeStep: " << detectorParams->adaptiveThreshWinSizeStep << endl;
cout << "adaptiveThreshConstant: " << detectorParams->adaptiveThreshConstant << endl;
cout << "minMarkerPerimeterRate: " << detectorParams->minMarkerPerimeterRate << endl;
cout << "maxMarkerPerimeterRate: " << detectorParams->maxMarkerPerimeterRate << endl;
cout << "polygonalApproxAccuracyRate: " << detectorParams->polygonalApproxAccuracyRate << endl;
cout << "minCornerDistanceRate: " << detectorParams->minCornerDistanceRate << endl;
cout << "minDistanceToBorder: " << detectorParams->minDistanceToBorder << endl;
cout << "minMarkerDistanceRate: " << detectorParams->minMarkerDistanceRate << endl;
cout << "cornerRefinementMethod: " << detectorParams->cornerRefinementMethod << endl;
cout << "cornerRefinementWinSize: " << detectorParams->cornerRefinementWinSize << endl;
cout << "cornerRefinementMaxIterations: " << detectorParams->cornerRefinementMaxIterations << endl;
cout << "cornerRefinementMinAccuracy: " << detectorParams->cornerRefinementMinAccuracy << endl;
cout << "markerBorderBits: " << detectorParams->markerBorderBits << endl;
cout << "perspectiveRemovePixelPerCell: " << detectorParams->perspectiveRemovePixelPerCell << endl;
cout << "perspectiveRemoveIgnoredMarginPerCell: " << detectorParams->perspectiveRemoveIgnoredMarginPerCell << endl;
cout << "maxErroneousBitsInBorderRate: " << detectorParams->maxErroneousBitsInBorderRate << endl;
cout << "minOtsuStdDev: " << detectorParams->minOtsuStdDev << endl;
cout << "errorCorrectionRate: " << detectorParams->errorCorrectionRate << endl;
cout << "aprilTagQuadDecimate: " << detectorParams->aprilTagQuadDecimate << endl;
cout << "aprilTagQuadSigma: " << detectorParams->aprilTagQuadSigma << endl;
cout << "aprilTagMinClusterPixels: " << detectorParams->aprilTagMinClusterPixels << endl;
cout << "aprilTagMaxNmaxima: " << detectorParams->aprilTagMaxNmaxima << endl;
cout << "aprilTagCriticalRad: " << detectorParams->aprilTagCriticalRad << endl;
cout << "aprilTagMaxLineFitMse: " << detectorParams->aprilTagMaxLineFitMse << endl;
cout << "aprilTagMinWhiteBlackDiff: " << detectorParams->aprilTagMinWhiteBlackDiff << endl;
cout << "aprilTagDeglitch: " << detectorParams->aprilTagDeglitch << endl;
cout << "detectInvertedMarker: " << detectorParams->detectInvertedMarker << endl;
Ptr<aruco::Dictionary> dictionary = aruco::getPredefinedDictionary(tag_family);
Mat frame, gray;
int save_frame = 0, frame_count = 0;
bool quit = false, pause = false;
vector<double> times;
while (!quit) {
capture >> frame;
if (frame.empty()) {
break;
}
TickMeter tm;
tm.start();
cvtColor(frame, gray, COLOR_BGR2GRAY);
vector<int> ids;
vector<vector<Point2f> > corners, rejected;
aruco::detectMarkers(gray, dictionary, corners, ids, detectorParams, show_rejected ? rejected : noArray());
tm.stop();
times.push_back(tm.getTimeMilli());
if (verbose) {
cout << "\n================\nFrame: " << frame_count++ << endl;
for (size_t i = 0; i < corners.size(); i++) {
cout << "\ntag " << ids[i] << endl;
const Point2f& pt0 = corners[i][0];
const Point2f& pt1 = corners[i][1];
const Point2f& pt2 = corners[i][2];
const Point2f& pt3 = corners[i][3];
cout << "(" << pt0.x << ", " << pt0.y << ")" << endl;
cout << "(" << pt1.x << ", " << pt1.y << ")" << endl;
cout << "(" << pt2.x << ", " << pt2.y << ")" << endl;
cout << "(" << pt3.x << ", " << pt3.y << ")" << endl;
}
}
aruco::drawDetectedMarkers(frame, corners, ids);
if (show_rejected) {
aruco::drawDetectedMarkers(frame, rejected, noArray(), Scalar(100, 0, 255));
}
if (!save_directory.empty()) {
imwrite(format(string(save_directory + "/image_%04d.png").c_str(), save_frame++), frame);
}
imshow("ArUco module", frame);
int c = waitKey(pause ? 0 : 30);
if (c == 27) {
quit = true;
} else if (c == ' ') {
pause = !pause;
}
}
if (!times.empty()) {
double mean_time = accumulate(times.begin(), times.end(), 0.0)/times.size();
cout << "\nMean detection time: " << mean_time << " ms" << endl;
}
return 0;
}
/* Copyright (C) 2013-2016, The Regents of The University of Michigan.
All rights reserved.
This software was developed in the APRIL Robotics Lab under the
direction of Edwin Olson, [email protected]. This software may be
available under alternative licensing terms; contact the address above.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the Regents of The University of Michigan.
*/
#include <iostream>
#include <numeric>
#include "opencv2/opencv.hpp"
#include "apriltag.h"
#include "tag36h11.h"
#include "tag36h10.h"
#include "tag36artoolkit.h"
#include "tag25h9.h"
#include "tag25h7.h"
#include "common/getopt.h"
using namespace std;
using namespace cv;
int main(int argc, char *argv[])
{
getopt_t *getopt = getopt_create();
getopt_add_bool(getopt, 'h', "help", 0, "Show this help");
getopt_add_bool(getopt, 'd', "debug", 0, "Enable debugging output (slow)");
getopt_add_bool(getopt, 'q', "quiet", 0, "Reduce output");
getopt_add_string(getopt, 'f', "family", "tag36h11", "Tag family to use");
getopt_add_int(getopt, '\0', "border", "1", "Set tag family border size");
getopt_add_int(getopt, 't', "threads", "4", "Use this many CPU threads");
getopt_add_double(getopt, 'x', "decimate", "1.0", "Decimate input image by this factor");
getopt_add_double(getopt, 'b', "blur", "0.0", "Apply low-pass blur to input");
getopt_add_bool(getopt, '0', "refine-edges", 0, "Spend more time trying to align edges of tags");
getopt_add_bool(getopt, '1', "refine-decode", 0, "Spend more time trying to decode tags");
getopt_add_bool(getopt, '2', "refine-pose", 0, "Spend more time trying to precisely localize tags");
getopt_add_string(getopt, 'i', "input", "", "Path to input images or video");
getopt_add_int(getopt, 'c', "camera", "0", "Camera device number");
getopt_add_bool(getopt, 'v', "verbose", 0, "Print corners locations");
getopt_add_string(getopt, 's', "save", "", "Save directory");
if (!getopt_parse(getopt, argc, argv, 1) ||
getopt_get_bool(getopt, "help")) {
printf("Usage: %s [options]\n", argv[0]);
getopt_do_usage(getopt);
exit(0);
}
// Initialize camera
VideoCapture cap;
string intput_filename = getopt_get_string(getopt, "input");
if (intput_filename.empty()) {
cap.open(getopt_get_int(getopt, "camera"));
} else {
cap.open(intput_filename);
}
if (!cap.isOpened()) {
cerr << "Couldn't open video capture device" << endl;
return -1;
}
// Initialize tag detector with options
apriltag_family_t *tf = NULL;
const char *famname = getopt_get_string(getopt, "family");
if (!strcmp(famname, "tag36h11"))
tf = tag36h11_create();
else if (!strcmp(famname, "tag36h10"))
tf = tag36h10_create();
else if (!strcmp(famname, "tag36artoolkit"))
tf = tag36artoolkit_create();
else if (!strcmp(famname, "tag25h9"))
tf = tag25h9_create();
else if (!strcmp(famname, "tag25h7"))
tf = tag25h7_create();
else {
printf("Unrecognized tag family name. Use e.g. \"tag36h11\".\n");
exit(-1);
}
tf->black_border = getopt_get_int(getopt, "border");
apriltag_detector_t *td = apriltag_detector_create();
apriltag_detector_add_family(td, tf);
td->quad_decimate = getopt_get_double(getopt, "decimate");
td->quad_sigma = getopt_get_double(getopt, "blur");
td->nthreads = getopt_get_int(getopt, "threads");
td->debug = getopt_get_bool(getopt, "debug");
td->refine_edges = getopt_get_bool(getopt, "refine-edges");
td->refine_decode = getopt_get_bool(getopt, "refine-decode");
td->refine_pose = getopt_get_bool(getopt, "refine-pose");
bool verbose = getopt_get_bool(getopt, "verbose");
string save_directory = getopt_get_string(getopt, "save");
cout << "quad_decimate: " << td->quad_decimate << endl;
cout << "quad_sigma: " << td->quad_sigma << endl;
cout << "nthreads: " << td->nthreads << endl;
cout << "debug: " << td->debug << endl;
cout << "refine_edges: " << td->refine_edges << endl;
cout << "refine_decode: " << td->refine_decode << endl;
cout << "refine_pose: " << td->refine_pose << endl;
cout << "verbose: " << verbose << endl;
cout << "save_directory: " << save_directory << endl;
int save_frame = 0, frame_count = 0;
vector<double> times;
Mat frame, gray;
bool quit = false, pause = false;
while (!quit) {
cap >> frame;
if (frame.empty())
break;
TickMeter tm;
tm.start();
cvtColor(frame, gray, COLOR_BGR2GRAY);
// Make an image_u8_t header for the Mat data
image_u8_t im = { .width = gray.cols,
.height = gray.rows,
.stride = gray.cols,
.buf = gray.data
};
zarray_t *detections = apriltag_detector_detect(td, &im);
tm.stop();
times.push_back(tm.getTimeMilli());
if (verbose) {
cout << "\n================\nFrame: " << frame_count++ << endl;
}
// Draw detection outlines
for (int i = 0; i < zarray_size(detections); i++) {
apriltag_detection_t *det;
zarray_get(detections, i, &det);
line(frame, Point(det->p[0][0], det->p[0][1]),
Point(det->p[1][0], det->p[1][1]),
Scalar(0, 0xff, 0), 2);
line(frame, Point(det->p[0][0], det->p[0][1]),
Point(det->p[3][0], det->p[3][1]),
Scalar(0, 0, 0xff), 2);
line(frame, Point(det->p[1][0], det->p[1][1]),
Point(det->p[2][0], det->p[2][1]),
Scalar(0xff, 0, 0), 2);
line(frame, Point(det->p[2][0], det->p[2][1]),
Point(det->p[3][0], det->p[3][1]),
Scalar(0xff, 0, 0), 2);
if (verbose) {
cout << "\ntag " << det->id << endl;
cout << "(" << det->p[0][0] << ", " << det->p[0][1] << ")" << endl;
cout << "(" << det->p[1][0] << ", " << det->p[1][1] << ")" << endl;
cout << "(" << det->p[2][0] << ", " << det->p[2][1] << ")" << endl;
cout << "(" << det->p[3][0] << ", " << det->p[3][1] << ")" << endl;
}
stringstream ss;
ss << det->id;
String text = ss.str();
int fontface = FONT_HERSHEY_SCRIPT_SIMPLEX;
double fontscale = 1.0;
int baseline;
Size textsize = getTextSize(text, fontface, fontscale, 2,
&baseline);
putText(frame, text, Point(det->c[0]-textsize.width/2,
det->c[1]+textsize.height/2),
fontface, fontscale, Scalar(0xff, 0x99, 0), 2);
}
apriltag_detections_destroy(detections);
if (!save_directory.empty()) {
imwrite(format(string(save_directory + "/image_%04d.png").c_str(), save_frame++), frame);
}
imshow("Tag Detections", frame);
int c = waitKey(pause ? 0 : 30);
if (c == 27)
quit = true;
else if (c == ' ') {
pause = !pause;
}
}
if (!times.empty()) {
double mean_time = accumulate(times.begin(), times.end(), 0.0)/times.size();
cout << "\nMean detection time: " << mean_time << " ms" << endl;
}
apriltag_detector_destroy(td);
if (!strcmp(famname, "tag36h11"))
tag36h11_destroy(tf);
else if (!strcmp(famname, "tag36h10"))
tag36h10_destroy(tf);
else if (!strcmp(famname, "tag36artoolkit"))
tag36artoolkit_destroy(tf);
else if (!strcmp(famname, "tag25h9"))
tag25h9_destroy(tf);
else if (!strcmp(famname, "tag25h7"))
tag25h7_destroy(tf);
getopt_destroy(getopt);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment