Visual Servoing Platform version 3.7.0
Loading...
Searching...
No Matches
tutorial-rbt-sequence.cpp
1/*
2 * ViSP, open source Visual Servoing Platform software.
3 * Copyright (C) 2005 - 2024 by Inria. All rights reserved.
4 *
5 * This software is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 * See the file LICENSE.txt at the root directory of this source
10 * distribution for additional information about the GNU GPL.
11 *
12 * For using ViSP with software that can not be combined with the GNU
13 * GPL, please contact Inria about acquiring a ViSP Professional
14 * Edition License.
15 *
16 * See https://visp.inria.fr for more information.
17 *
18 * This software was developed at:
19 * Inria Rennes - Bretagne Atlantique
20 * Campus Universitaire de Beaulieu
21 * 35042 Rennes Cedex
22 * France
23 *
24 * If you have questions regarding the use of this file, please contact
25 * Inria at visp@inria.fr
26 *
27 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
28 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
29 */
31#include <iostream>
32#include <visp3/core/vpConfig.h>
33
34#if defined(VISP_HAVE_NLOHMANN_JSON)
35
36#include <visp3/core/vpException.h>
37#include <visp3/core/vpImageException.h>
38#include <visp3/core/vpIoTools.h>
39#include <visp3/core/vpRGBa.h>
40
41#include <visp3/io/vpVideoReader.h>
42#include <visp3/io/vpVideoWriter.h>
43
44#include <visp3/ar/vpPanda3DFrameworkManager.h>
45
46#include <visp3/rbt/vpRBTracker.h>
47
48#ifdef ENABLE_VISP_NAMESPACE
49using namespace VISP_NAMESPACE_NAME;
50#endif
51
52#include "render-based-tutorial-utils.h"
53
55{
57 { }
58
60 {
61 parser
62 .addArgument("--color", colorSequence, true, "The color sequence (in video reader format, eg., /path/to/I\%04d.png)")
63 .addArgument("--depth", depthFolder, false, "The depth images associated to the color sequence. Frames should be aligned")
64 .addArgument("--start", startFrame, false, "The first frame of the sequence")
65 .addArgument("--step", frameStep, false, "How many frames should be read between calls to the tracker")
66 .addFlag("--step-by-step", stepByStep, "Go through the sequence interactively, frame by frame");
67 }
68
70 {
71 if (colorSequence.empty()) {
72 throw vpException(vpException::badValue, "Input sequence should not be empty");
73 }
74 }
75
76 std::string colorSequence;
77 std::string depthFolder;
79 unsigned int frameStep;
81};
82
83int main(int argc, const char **argv)
84{
85 vpRBTrackerTutorial::BaseArguments baseArgs;
86 CmdArguments sequenceArgs;
87 vpRBTrackerTutorial::vpRBExperimentLogger logger;
88 vpRBTrackerTutorial::vpRBExperimentPlotter plotter;
89
90 vpJsonArgumentParser parser("Tutorial showing how to use the Render-Based Tracker on an offline sequence", "--config", "/");
91 baseArgs.registerArguments(parser);
92 sequenceArgs.registerArguments(parser);
93 logger.registerArguments(parser);
94 plotter.registerArguments(parser);
95
96 parser.parse(argc, argv);
97
98 baseArgs.postProcessArguments();
99 sequenceArgs.postProcessArguments();
100 plotter.postProcessArguments(baseArgs.display);
101
102 if (baseArgs.enableRenderProfiling) {
103 vpRBTrackerTutorial::enableRendererProfiling();
104 }
105
106 baseArgs.display = true;
107 // Get the option values
108
109 logger.startLog();
110
111 // Set tracking and rendering parameters
113
115 tracker.loadConfigurationFile(baseArgs.trackerConfiguration);
116 tracker.startTracking();
117 cam = tracker.getCameraParameters();
118
119 // VideoReader to read images from disk
120 vpImage<vpRGBa> Icol;
121 vpVideoReader readerRGB;
122 std::cout << "Input video" << std::endl;
123 std::cout << " Filename : " << sequenceArgs.colorSequence << std::endl;
124 if (sequenceArgs.startFrame >= 0) {
125 readerRGB.setFirstFrameIndex(sequenceArgs.startFrame);
126 std::cout << " First frame: " << sequenceArgs.startFrame << std::endl;
127 }
128 readerRGB.setFileName(sequenceArgs.colorSequence);
129 readerRGB.open(Icol);
130 readerRGB.acquire(Icol);
131
132 if (sequenceArgs.startFrame < 0) {
133 std::cout << " First frame: " << readerRGB.getFirstFrameIndex() << std::endl;
134 }
135
136 const int width = readerRGB.getWidth();
137 const int height = readerRGB.getHeight();
138
139 std::cout << " Image size : " << width << " x " << height << std::endl;
140
141 vpImage<unsigned char> Id(height, width);
142 vpImage<float> depth(0, 0);
143 vpImage<unsigned char> depthDisplay(height, width);
144 vpImage<unsigned char> IProbaDisplay(height, width);
145 vpImage<vpRGBa> IRender(height, width);
146 vpImage<vpRGBa> InormDisplay(height, width);
147 vpImage<unsigned char> ICannyDisplay(height, width);
148
149 vpImageConvert::convert(Icol, Id);
150
151 // Main window creation and displaying
152
153 std::vector<std::shared_ptr<vpDisplay>> displays, debugDisplays;
154
155 if (baseArgs.display) {
156 displays = vpRBTrackerTutorial::createDisplays(Id, Icol, depthDisplay, IProbaDisplay);
157 if (baseArgs.debugDisplay) {
158 debugDisplays = vpDisplayFactory::makeDisplayGrid(
159 1, 3,
160 0, 0,
161 20, 20,
162 "Normals in object frame", InormDisplay,
163 "Depth canny", ICannyDisplay,
164 "Color render", IRender
165 );
166 }
167 plotter.init(displays);
168 }
169
171
172 nlohmann::json result = nlohmann::json::array();
173
174 // Manual initialization of the tracker
175 std::cout << "Starting init" << std::endl;
176
177 if (baseArgs.hasInlineInit()) {
178 tracker.setPose(baseArgs.cMoInit);
179 }
180 else if (baseArgs.display) {
181 tracker.initClick(Id, baseArgs.initFile, true);
182 }
183 else {
184 throw vpException(vpException::notImplementedError, "Cannot initialize tracking: no auto init function provided");
185 }
186
187 if (baseArgs.display) {
189 }
190
191 int im = sequenceArgs.startFrame;
192 unsigned int iter = 1;
193 // Main tracking loop
194 double expStart = vpTime::measureTimeMs();
195 bool quit = false;
196 while (!quit) {
197 double frameStart = vpTime::measureTimeMs();
198 // Acquire images
199 for (unsigned int sp = 0; sp < sequenceArgs.frameStep; ++sp) {
200 readerRGB.acquire(Icol);
201 vpImageConvert::convert(Icol, Id);
202 if (!sequenceArgs.depthFolder.empty()) {
203 std::string depthName = vpIoTools::formatString(sequenceArgs.depthFolder + "/%06d.npy", im);
204 visp::cnpy::NpyArray npz_data = visp::cnpy::npy_load(depthName);
205 vpImage<uint16_t> dataArray(npz_data.data<uint16_t>(), npz_data.shape[0], npz_data.shape[1], false);
206 float scale = 9.999999747378752e-05;
207 depth.resize(dataArray.getHeight(), dataArray.getWidth());
208 depthDisplay.resize(dataArray.getHeight(), dataArray.getWidth());
209#ifdef VISP_HAVE_OPENMP
210#pragma omp parallel for
211#endif
212 for (int i = 0; i < static_cast<int>(dataArray.getSize()); ++i) {
213 float value = static_cast<float>(dataArray.bitmap[i]) * scale;
214 depth.bitmap[i] = value;
215 depthDisplay.bitmap[i] = value > baseArgs.maxDepthDisplay ? 0.f : static_cast<unsigned char>((depth.bitmap[i] / baseArgs.maxDepthDisplay) * 255.f);
216 }
217 }
218 }
219
220 // Pose tracking
221 double trackingStart = vpTime::measureTimeMs();
222 vpRBTrackingResult trackingResult;
223 if (depth.getSize() == 0) {
224 trackingResult = tracker.track(Id, Icol);
225 }
226 else {
227 trackingResult = tracker.track(Id, Icol, depth);
228 }
229
230 switch (trackingResult.getStoppingReason()) {
231 case vpRBTrackingStoppingReason::EXCEPTION:
232 {
233 std::cout << "Encountered an exception during tracking, pose was not updated" << std::endl;
234 break;
235 }
236 case vpRBTrackingStoppingReason::NOT_ENOUGH_FEATURES:
237 {
238 std::cout << "There were not enough feature to perform tracking" << std::endl;
239 break;
240 }
241 case vpRBTrackingStoppingReason::OBJECT_NOT_IN_IMAGE:
242 {
243 std::cout << "Object is not in image" << std::endl;
244 break;
245 }
246 case vpRBTrackingStoppingReason::CONVERGENCE_CRITERION:
247 {
248 std::cout << "Convergence criterion reached:" << std::endl;
249 std::cout << "- Num iterations: " << trackingResult.getNumIterations() << std::endl;
250 std::cout << "- Convergence criterion: " << *(trackingResult.getConvergenceMetricValues().end() - 1) << std::endl;
251 break;
252 }
253 case vpRBTrackingStoppingReason::MAX_ITERS:
254 {
255 break;
256 }
257 default:
258 {
259 }
260 }
261
262 std::cout << "Tracking took " << vpTime::measureTimeMs() - trackingStart << "ms" << std::endl;
263
264 if (baseArgs.display) {
265 if (baseArgs.debugDisplay) {
266 const vpRBFeatureTrackerInput &lastFrame = tracker.getMostRecentFrame();
267
268 vpRBTrackerTutorial::displayNormals(lastFrame.renders.normals, InormDisplay);
269
270 vpRBTrackerTutorial::displayCanny(lastFrame.renders.silhouetteCanny, ICannyDisplay, lastFrame.renders.isSilhouette);
271 if (lastFrame.renders.color.getSize() > 0) {
272 IRender = lastFrame.renders.color;
273 vpDisplay::display(IRender);
274 vpDisplay::flush(IRender);
275 }
276 }
277
279 vpDisplay::displayText(Id, 20, 20, "Click to quit", vpColor::red);
280 vpDisplay::display(Icol);
281
282 tracker.display(Id, Icol, depthDisplay);
283 tracker.displayMask(IProbaDisplay);
284 vpDisplay::display(IProbaDisplay);
285 vpDisplay::displayFrame(Icol, cMo, cam, 0.05, vpColor::none, 2);
286 vpDisplay::flush(Icol);
288 vpDisplay::flush(IProbaDisplay);
289 if (depth.getSize() > 0) {
290 vpDisplay::display(depthDisplay);
291 vpDisplay::flush(depthDisplay);
292 }
293 }
294
295 tracker.getPose(cMo);
296 result.push_back(cMo);
297
298 logger.logFrame(tracker, iter, Id, Icol, depthDisplay, IProbaDisplay);
299
300 if (sequenceArgs.stepByStep && baseArgs.display) {
301 vpDisplay::getClick(Id, true);
302 }
303
304 std::cout << "Iter: " << iter << std::endl;
305 ++im;
306 ++iter;
307 if (im > readerRGB.getLastFrameIndex()) {
308 quit = true;
309 std::cout << "End of video reached" << std::endl;
310 }
311
312 double frameEnd = vpTime::measureTimeMs();
313 std::cout << "Frame took: " << frameEnd - frameStart << "ms" << std::endl;
314 plotter.plot(tracker, (frameEnd - expStart) / 1000.0);
315
316 if (vpDisplay::getClick(Id, false)) {
317 quit = true;
318 }
319 }
320
321 logger.close();
323
324 return EXIT_SUCCESS;
325}
326
327#else
328int main()
329{
330 std::cout << "This tutorial requires nlohmann_json 3rdparty." << std::endl;
331}
332#endif
Generic class defining intrinsic camera parameters.
static const vpColor red
Definition vpColor.h:198
static const vpColor none
Definition vpColor.h:210
static bool getClick(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 flush(const vpImage< unsigned char > &I)
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.
Definition vpException.h:60
@ badValue
Used to indicate that a value is not in the allowed range.
Definition vpException.h:73
@ notImplementedError
Not implemented.
Definition vpException.h:69
unsigned int getWidth() const
Return the number of columns in the image.
unsigned int getHeight() const
Return the number of rows in the image.
Implementation of an homogeneous matrix and operations on such kind of matrices.
static void convert(const vpImage< unsigned char > &src, vpImage< vpRGBa > &dest)
Definition of the vpImage class member functions.
Definition vpImage.h:131
unsigned int getSize() const
Definition vpImage.h:221
static std::string formatString(const std::string &name, unsigned int val)
Command line argument parsing with support for JSON files. If a JSON file is supplied,...
static vpPanda3DFrameworkManager & getInstance()
All the data related to a single tracking frame. This contains both the input data (from a real camer...
vpRBRenderData renders
camera parameters
Class implementing the Render-Based Tracker (RBT).
Definition vpRBTracker.h:87
vpRBTrackingStoppingReason getStoppingReason() const
const std::vector< double > & getConvergenceMetricValues() const
unsigned int getNumIterations() const
Class that enables to manipulate easily a video file or a sequence of images. As it inherits from the...
long getLastFrameIndex()
void open(vpImage< vpRGBa > &I) VP_OVERRIDE
void setFileName(const std::string &filename)
void setFirstFrameIndex(const long first_frame)
long getFirstFrameIndex()
void acquire(vpImage< vpRGBa > &I) VP_OVERRIDE
VISP_EXPORT NpyArray npy_load(const std::string &fname)
std::vector< std::shared_ptr< vpDisplay > > makeDisplayGrid(unsigned int rows, unsigned int cols, unsigned int startX, unsigned int startY, unsigned int paddingX, unsigned int paddingY, Args &... args)
Create a grid of displays, given a set of images. All the displays will be initialized in the correct...
VISP_EXPORT double measureTimeMs()
void registerArguments(vpJsonArgumentParser &parser)
std::vector< size_t > shape
Definition vpIoTools.h:170
vpImage< vpRGBa > color
vpImage< vpRGBf > normals
vpImage< unsigned char > isSilhouette
Image containing the orientation of the gradients.
vpImage< float > silhouetteCanny