#include <iostream>
#include <visp3/core/vpConfig.h>
#if ((__cplusplus >= 201703L) || (defined(_MSVC_LANG) && (_MSVC_LANG >= 201703L))) && \
defined(VISP_HAVE_NLOHMANN_JSON) && defined(VISP_HAVE_OPENCV) && defined(HAVE_OPENCV_VIDEOIO) && \
defined(HAVE_OPENCV_DNN) && (defined(VISP_HAVE_X11) || defined(VISP_HAVE_GDI) || defined(HAVE_OPENCV_HIGHGUI)) && \
defined(VISP_HAVE_THREADS)
#include <optional>
#include <visp3/core/vpIoTools.h>
#include <visp3/detection/vpDetectorDNNOpenCV.h>
#include <visp3/gui/vpDisplayGDI.h>
#include <visp3/gui/vpDisplayOpenCV.h>
#include <visp3/gui/vpDisplayX.h>
#include <visp3/dnn_tracker/vpMegaPose.h>
#include <visp3/dnn_tracker/vpMegaPoseTracker.h>
#include <visp3/io/vpJsonArgumentParser.h>
#include VISP_NLOHMANN_JSON(json.hpp)
#include <opencv2/videoio.hpp>
using json = nlohmann::json;
#ifdef ENABLE_VISP_NAMESPACE
#endif
{
const float r = ((float)high.
R - (
float)low.
R) * f;
const float g = ((float)high.
G - (
float)low.
G) * f;
const float b = ((float)high.
B - (
float)low.
B) * f;
return vpColor((
unsigned char)r, (
unsigned char)g, (
unsigned char)b);
}
{
const unsigned top =
static_cast<unsigned>(I.
getHeight() * 0.85f);
const unsigned height =
static_cast<unsigned>(I.
getHeight() * 0.1f);
const unsigned left =
static_cast<unsigned>(I.
getWidth() * 0.05f);
const unsigned width =
static_cast<unsigned>(I.
getWidth() * 0.5f);
vpRect full(left, top, width, height);
vpRect scoreRect(left, top, width * score, height);
const vpColor c = interpolate(low, high, score);
}
{
for (
unsigned int i = 0; i < I.
getHeight(); ++i) {
for (
unsigned int j = 0; j < I.
getWidth(); ++j) {
if (overlay[i][j] != black) {
I[i][j] = overlay[i][j];
}
}
}
}
std::optional<vpRect> detectObjectForInitMegaposeDnn(vpDetectorDNNOpenCV &detector, const cv::Mat &I,
const std::string &detectionLabel,
std::optional<vpMegaPoseEstimate> previousEstimate)
{
std::vector<vpDetectorDNNOpenCV::DetectedFeatures2D> detections_vec;
detector.detect(I, detections_vec);
std::vector<vpDetectorDNNOpenCV::DetectedFeatures2D> matchingDetections;
for (const auto &detection : detections_vec) {
std::optional<std::string> classnameOpt = detection.getClassName();
if (classnameOpt) {
if (*classnameOpt == detectionLabel) {
matchingDetections.push_back(detection);
}
}
}
if (matchingDetections.size() == 0) {
return std::nullopt;
}
else if (matchingDetections.size() == 1) {
return matchingDetections[0].getBoundingBox();
}
else {
if (previousEstimate) {
double bestDist = 10000.f;
const vpImagePoint previousCenter = (*previousEstimate).boundingBox.getCenter();
for (const auto &detection : matchingDetections) {
const vpRect detectionBB = detection.getBoundingBox();
if (matchDist < bestDist) {
bestDist = matchDist;
best = detectionBB;
}
}
return best;
}
else {
double highestConf = 0.0;
for (const auto &detection : matchingDetections) {
const double conf = detection.getConfidenceScore();
if (conf > highestConf) {
highestConf = conf;
best = detection.getBoundingBox();
}
}
return best;
}
}
return std::nullopt;
}
std::optional<vpRect> detectObjectForInitMegaposeClick(
const vpImage<vpRGBa> &I)
{
if (startLabelling) {
vpRect bb(topLeft, bottomRight);
return bb;
}
else {
return std::nullopt;
}
}
enum DetectionMethod
{
UNKNOWN,
CLICK,
DNN
};
NLOHMANN_JSON_SERIALIZE_ENUM(DetectionMethod, {
{UNKNOWN, nullptr},
{CLICK, "click"},
{DNN, "dnn"} }
);
int main(int argc, const char *argv[])
{
unsigned width = 640, height = 480;
std::string videoDevice = "0";
std::string megaposeAddress = "127.0.0.1";
unsigned megaposePort = 5555;
int refinerIterations = 1, coarseNumSamples = 576;
double reinitThreshold = 0.2;
DetectionMethod detectionMethod = DetectionMethod::UNKNOWN;
std::string detectorModelPath = "path/to/model.onnx", detectorConfig = "none";
std::string detectorFramework = "onnx", detectorTypeString = "yolov7";
std::string objectName = "cube";
std::vector<std::string> labels = { "cube" };
float detectorMeanR = 0.f, detectorMeanG = 0.f, detectorMeanB = 0.f;
float detectorConfidenceThreshold = 0.65f, detectorNmsThreshold = 0.5f, detectorFilterThreshold = -0.25f;
float detectorScaleFactor = 0.0039f;
bool detectorSwapRB = false;
parser.addArgument("width", width, true, "The image width")
.addArgument("height", height, true, "The image height")
.addArgument("camera", cam, true, "The camera intrinsic parameters. Should correspond to a perspective projection model without distortion.")
.addArgument("video-device", videoDevice, true, "Video device")
.addArgument("object", objectName, true, "Name of the object to track with megapose.")
.addArgument("detectionMethod", detectionMethod, true, "How to perform detection of the object to get the bounding box:"
" \"click\" for user labelling, \"dnn\" for dnn detection.")
.addArgument("reinitThreshold", reinitThreshold, false, "If the Megapose score falls below this threshold, then a reinitialization is be required."
" Should be between 0 and 1")
.addArgument("megapose/address", megaposeAddress, true, "IP address of the Megapose server.")
.addArgument("megapose/port", megaposePort, true, "Port on which the Megapose server listens for connections.")
.addArgument("megapose/refinerIterations", refinerIterations, false, "Number of Megapose refiner model iterations."
"A higher count may lead to better accuracy, at the cost of more processing time")
.addArgument("megapose/initialisationNumSamples", coarseNumSamples, false, "Number of Megapose renderings used for the initial pose estimation.")
.addArgument("detector/model-path", detectorModelPath, true, "Path to the model")
.addArgument("detector/config", detectorConfig, true, "Path to the model configuration. Set to none if config is not required.")
.addArgument("detector/framework", detectorFramework, true, "Detector framework")
.addArgument("detector/type", detectorTypeString, true, "Detector type")
.addArgument("detector/labels", labels, true, "Detection class labels")
.addArgument("detector/mean/red", detectorMeanR, false, "Detector mean red component. Used to normalize image")
.addArgument("detector/mean/green", detectorMeanG, false, "Detector mean green component. Used to normalize image")
.addArgument("detector/mean/blue", detectorMeanB, false, "Detector mean red component. Used to normalize image")
.addArgument("detector/confidenceThreshold", detectorConfidenceThreshold, false, "Detector confidence threshold. "
"When a detection with a confidence below this threshold, it is ignored")
.addArgument("detector/nmsThreshold", detectorNmsThreshold, false, "Detector non maximal suppression threshold.")
.addArgument("detector/filterThreshold", detectorFilterThreshold, false)
.addArgument("detector/scaleFactor", detectorScaleFactor, false, "Pixel intensity rescaling factor. If set to 1/255, then pixel values are between 0 and 1.")
.addArgument("detector/swapRedAndBlue", detectorSwapRB, false, "Whether to swap red and blue channels before feeding the image to the detector.");
parser.parse(argc, argv);
}
if (detectionMethod == DetectionMethod::UNKNOWN) {
}
cv::VideoCapture capture;
bool isLiveCapture;
bool hasCaptureOpeningSucceeded;
double videoFrametime = 0;
hasCaptureOpeningSucceeded = capture.open(std::atoi(videoDevice.c_str()));
isLiveCapture = true;
}
else {
hasCaptureOpeningSucceeded = capture.open(videoDevice);
isLiveCapture = false;
double fps = capture.get(cv::CAP_PROP_FPS);
videoFrametime = (1.0 / fps) * 1000.0;
}
if (!hasCaptureOpeningSucceeded) {
std::cout << "Capture from camera: " << videoDevice << " didn't work" << std::endl;
return EXIT_FAILURE;
}
#if defined(VISP_HAVE_X11)
vpDisplayX d;
#elif defined(VISP_HAVE_GDI)
#elif defined(HAVE_OPENCV_HIGHGUI)
#endif
#if (VISP_HAVE_OPENCV_VERSION >= 0x030403) && defined(HAVE_OPENCV_DNN) && \
((__cplusplus >= 201703L) || (defined(_MSVC_LANG) && (_MSVC_LANG >= 201703L)))
vpDetectorDNNOpenCV::DNNResultsParsingType detectorType =
vpDetectorDNNOpenCV::dnnResultsParsingTypeFromString(detectorTypeString);
vpDetectorDNNOpenCV::NetConfig netConfig(detectorConfidenceThreshold, detectorNmsThreshold, labels,
cv::Size(width, height), detectorFilterThreshold);
vpDetectorDNNOpenCV dnn(netConfig, detectorType);
if (detectionMethod == DetectionMethod::DNN) {
dnn.readNet(detectorModelPath, detectorConfig, detectorFramework);
dnn.setMean(detectorMeanR, detectorMeanG, detectorMeanB);
dnn.setScaleFactor(detectorScaleFactor);
dnn.setSwapRB(detectorSwapRB);
}
#endif
std::shared_ptr<vpMegaPose> megapose;
try {
megapose = std::make_shared<vpMegaPose>(megaposeAddress, megaposePort, cam, height, width);
}
catch (...) {
}
megapose->setCoarseNumSamples(coarseNumSamples);
const std::vector<std::string> allObjects = megapose->getObjectNames();
if (std::find(allObjects.begin(), allObjects.end(), objectName) == allObjects.end()) {
}
std::future<vpMegaPoseEstimate> trackerFuture;
cv::Mat frame;
bool callMegapose = true;
bool initialized = false;
bool tracking = false;
bool overlayModel = true;
std::string overlayMode = "full";
std::vector<double> megaposeTimes;
std::vector<double> frameTimes;
double megaposeStartTime = 0.0;
while (true) {
capture >> frame;
if (frame.empty())
break;
}
else {
}
if (!callMegapose && trackerFuture.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {
megaposeEstimate = trackerFuture.get();
if (tracking) {
}
callMegapose = true;
tracking = true;
if (overlayModel) {
overlayImage = megapose->viewObjects({ objectName }, { megaposeEstimate.
cTo }, overlayMode);
}
if (megaposeEstimate.
score < reinitThreshold) {
initialized = false;
}
}
if (callMegapose) {
if (!initialized) {
tracking = false;
std::optional<vpRect> detection = std::nullopt;
#if (VISP_HAVE_OPENCV_VERSION >= 0x030403) && defined(HAVE_OPENCV_DNN) && \
((__cplusplus >= 201703L) || (defined(_MSVC_LANG) && (_MSVC_LANG >= 201703L)))
if (detectionMethod == DetectionMethod::DNN) {
detection = detectObjectForInitMegaposeDnn(
dnn, frame, objectName, initialized ? std::optional(megaposeEstimate) : std::nullopt);
}
#endif
if (detectionMethod == DetectionMethod::CLICK) {
detection = detectObjectForInitMegaposeClick(I);
}
if (detection) {
initialized = true;
lastDetection = *detection;
trackerFuture = megaposeTracker.init(I, lastDetection);
callMegapose = false;
}
}
else {
trackerFuture = megaposeTracker.track(I);
callMegapose = false;
}
}
std::string keyboardEvent;
if (keyPressed) {
if (keyboardEvent == "t") {
overlayModel = !overlayModel;
}
else if (keyboardEvent == "w") {
overlayMode = overlayMode == "full" ? "wireframe" : "full";
}
}
if (tracking) {
if (overlayModel) {
overlayRender(I, overlayImage);
}
displayScore(I, megaposeEstimate.
score);
}
break;
}
}
if (!isLiveCapture) {
vpTime::wait(std::max<double>(0.0, videoFrametime - (frameEnd - frameStart)));
}
}
std::cout <<
"Average frame time: " <<
vpMath::getMean(frameTimes) << std::endl;
std::cout <<
"Average time between Megapose calls: " <<
vpMath::getMean(megaposeTimes) << std::endl;
}
#else
int main()
{
std::cout << "Compile ViSP with the DNN tracker module, the JSON 3rd party library and the OpenCV detection module" << std::endl;
return EXIT_SUCCESS;
}
#endif
Generic class defining intrinsic camera parameters.
@ perspectiveProjWithoutDistortion
Perspective projection without distortion model.
vpCameraParametersProjType get_projModel() const
Class to define RGB colors available for display functionalities.
static const vpColor none
static const vpColor green
Display for windows using GDI (available on any windows 32 platform).
The vpDisplayOpenCV allows to display image using the OpenCV library. Thus to enable this class OpenC...
void init(vpImage< unsigned char > &I, int winx=-1, int winy=-1, const std::string &title="") VP_OVERRIDE
static bool getClick(const vpImage< unsigned char > &I, bool blocking=true)
static bool getKeyboardEvent(const vpImage< unsigned char > &I, bool blocking=true)
static void display(const vpImage< unsigned char > &I)
static void displayFrame(const vpImage< unsigned char > &I, const vpHomogeneousMatrix &cMo, const vpCameraParameters &cam, double size, const vpColor &color=vpColor::none, unsigned int thickness=1, const vpImagePoint &offset=vpImagePoint(0, 0), const std::string &frameName="", const vpColor &textColor=vpColor::black, const vpImagePoint &textOffset=vpImagePoint(15, 15))
static void displayCross(const vpImage< unsigned char > &I, const vpImagePoint &ip, unsigned int size, const vpColor &color, unsigned int thickness=1)
static void setTitle(const vpImage< unsigned char > &I, const std::string &windowtitle)
static void flush(const vpImage< unsigned char > &I)
static void displayRectangle(const vpImage< unsigned char > &I, const vpImagePoint &topLeft, unsigned int width, unsigned int height, const vpColor &color, bool fill=false, unsigned int thickness=1)
static void displayText(const vpImage< unsigned char > &I, const vpImagePoint &ip, const std::string &s, const vpColor &color)
error that can be emitted by ViSP classes.
@ badValue
Used to indicate that a value is not in the allowed range.
static void convert(const vpImage< unsigned char > &src, vpImage< vpRGBa > &dest)
Class that defines a 2D point in an image. This class is useful for image processing and stores only ...
static double distance(const vpImagePoint &iP1, const vpImagePoint &iP2)
unsigned int getWidth() const
unsigned int getSize() const
unsigned int getHeight() const
Command line argument parsing with support for JSON files. If a JSON file is supplied,...
static double getMean(const std::vector< double > &v)
static bool isNumber(const std::string &str)
A simplified interface to track a single object with MegaPose. This tracker works asynchronously: A c...
unsigned char B
Blue component.
unsigned char R
Red component.
unsigned char G
Green component.
Defines a rectangle in the plane.
void getCenter(double &x, double &y) const
VISP_EXPORT int wait(double t0, double t)
VISP_EXPORT double measureTimeMs()