wrapper.hpp 65.8 KB
Newer Older
1 2
#ifndef OPENPOSE_WRAPPER_WRAPPER_HPP
#define OPENPOSE_WRAPPER_WRAPPER_HPP
G
gineshidalgo99 已提交
3

4
#include <openpose/core/common.hpp>
G
Gines Hidalgo 已提交
5
#include <openpose/thread/headers.hpp>
6 7 8 9 10
#include <openpose/wrapper/wrapperStructFace.hpp>
#include <openpose/wrapper/wrapperStructHand.hpp>
#include <openpose/wrapper/wrapperStructInput.hpp>
#include <openpose/wrapper/wrapperStructOutput.hpp>
#include <openpose/wrapper/wrapperStructPose.hpp>
G
gineshidalgo99 已提交
11 12 13

namespace op
{
G
gineshidalgo99 已提交
14 15
    /**
     * Wrapper: OpenPose all-in-one wrapper template class.
16 17
     * Wrapper allows the user to set up the input (video, webcam, custom input, etc.), pose, face and/or hands
     * estimation and rendering, and output (integrated small GUI, custom output, etc.).
G
gineshidalgo99 已提交
18 19 20
     *
     * This function can be used in 2 ways:
     *     - Synchronous mode: call the full constructor with your desired input and output workers.
21 22
     *     - Asynchronous mode: call the empty constructor Wrapper() + use the emplace and pop functions to push the
     *       original frames and retrieve the processed ones.
G
gineshidalgo99 已提交
23
     *     - Mix of them:
24 25
     *         - Synchronous input + asynchronous output: call the constructor Wrapper(ThreadManagerMode::Synchronous,
     *           workersInput, {}, true)
G
gineshidalgo99 已提交
26 27 28
     *         - Asynchronous input + synchronous output: call the constructor
     *           Wrapper(ThreadManagerMode::Synchronous, nullptr, workersOutput, irrelevantBoolean, true)
     */
G
gineshidalgo99 已提交
29 30 31
    template<typename TDatums,
             typename TWorker = std::shared_ptr<Worker<std::shared_ptr<TDatums>>>,
             typename TQueue = Queue<std::shared_ptr<TDatums>>>
G
gineshidalgo99 已提交
32 33 34
    class Wrapper
    {
    public:
G
gineshidalgo99 已提交
35 36
        /**
         * Constructor.
37 38 39 40
         * @param threadManagerMode Thread syncronization mode. If set to ThreadManagerMode::Synchronous, everything
         * will run inside the Wrapper. If ThreadManagerMode::Synchronous(In/Out), then input (frames producer) and/or
         * output (GUI, writing results, etc.) will be controlled outside the Wrapper class by the user. See
         * ThreadManagerMode for a detailed explanation of when to use each one.
G
gineshidalgo99 已提交
41 42 43 44 45 46 47
         */
        explicit Wrapper(const ThreadManagerMode threadManagerMode = ThreadManagerMode::Synchronous);

        /**
         * Destructor.
         * It automatically frees resources.
         */
G
gineshidalgo99 已提交
48 49
        ~Wrapper();

G
gineshidalgo99 已提交
50 51 52
        /**
         * Disable multi-threading.
         * Useful for debugging and logging, all the Workers will run in the same thread.
53 54
         * Note that workerOnNewThread (argument for setWorkerInput, setWorkerPostProcessing and setWorkerOutput) will
         * not make any effect.
G
gineshidalgo99 已提交
55 56 57 58 59 60
         */
        void disableMultiThreading();

        /**
         * Add an user-defined extra Worker as frames generator.
         * @param worker TWorker to be added.
61 62
         * @param workerOnNewThread Whether to add this TWorker on a new thread (if it is computationally demanding) or
         * simply reuse existing threads (for light functions). Set to true if the performance time is unknown.
G
gineshidalgo99 已提交
63
         */
G
gineshidalgo99 已提交
64 65
        void setWorkerInput(const TWorker& worker, const bool workerOnNewThread = true);

G
gineshidalgo99 已提交
66 67 68
        /**
         * Add an user-defined extra Worker as frames post-processor.
         * @param worker TWorker to be added.
69 70
         * @param workerOnNewThread Whether to add this TWorker on a new thread (if it is computationally demanding) or
         * simply reuse existing threads (for light functions). Set to true if the performance time is unknown.
G
gineshidalgo99 已提交
71
         */
G
gineshidalgo99 已提交
72 73
        void setWorkerPostProcessing(const TWorker& worker, const bool workerOnNewThread = true);

G
gineshidalgo99 已提交
74 75 76
        /**
         * Add an user-defined extra Worker as frames consumer (custom display and/or saving).
         * @param worker TWorker to be added.
77 78
         * @param workerOnNewThread Whether to add this TWorker on a new thread (if it is computationally demanding) or
         * simply reuse existing threads (for light functions). Set to true if the performance time is unknown.
G
gineshidalgo99 已提交
79
         */
G
gineshidalgo99 已提交
80 81
        void setWorkerOutput(const TWorker& worker, const bool workerOnNewThread = true);

82 83
        // If output is not required, just use this function until the renderOutput argument. Keep the default values
        // for the other parameters in order not to display/save any output.
G
gineshidalgo99 已提交
84
        void configure(const WrapperStructPose& wrapperStructPose,
85
                       // Producer: set producerSharedPtr=nullptr or use default WrapperStructInput{} to disable input
86 87 88 89 90 91 92
                       const WrapperStructInput& wrapperStructInput,
                       // Consumer (keep default values to disable any output)
                       const WrapperStructOutput& wrapperStructOutput = WrapperStructOutput{});

        // Similar to the previos configure, but it includes hand extraction and rendering
        void configure(const WrapperStructPose& wrapperStructPose,
                       // Hand (use the default WrapperStructHand{} to disable any hand detector)
93
                       const WrapperStructHand& wrapperStructHand,
94
                       // Producer: set producerSharedPtr=nullptr or use default WrapperStructInput{} to disable input
95 96 97 98 99 100 101
                       const WrapperStructInput& wrapperStructInput,
                       // Consumer (keep default values to disable any output)
                       const WrapperStructOutput& wrapperStructOutput = WrapperStructOutput{});

        // Similar to the previos configure, but it includes hand extraction and rendering
        void configure(const WrapperStructPose& wrapperStructPose,
                       // Face (use the default WrapperStructFace{} to disable any face detector)
102
                       const WrapperStructFace& wrapperStructFace,
103
                       // Producer: set producerSharedPtr=nullptr or use default WrapperStructInput{} to disable input
104
                       const WrapperStructInput& wrapperStructInput,
G
gineshidalgo99 已提交
105
                       // Consumer (keep default values to disable any output)
G
gineshidalgo99 已提交
106
                       const WrapperStructOutput& wrapperStructOutput = WrapperStructOutput{});
G
gineshidalgo99 已提交
107 108

        // Similar to the previos configure, but it includes hand extraction and rendering
G
gineshidalgo99 已提交
109
        void configure(const WrapperStructPose& wrapperStructPose = WrapperStructPose{},
110
                       // Face (use the default WrapperStructFace{} to disable any face detector)
111
                       const WrapperStructFace& wrapperStructFace = WrapperStructFace{},
112
                       // Hand (use the default WrapperStructHand{} to disable any hand detector)
113
                       const WrapperStructHand& wrapperStructHand = WrapperStructHand{},
114
                       // Producer: set producerSharedPtr=nullptr or use default WrapperStructInput{} to disable input
G
gineshidalgo99 已提交
115
                       const WrapperStructInput& wrapperStructInput = WrapperStructInput{},
G
gineshidalgo99 已提交
116
                       // Consumer (keep default values to disable any output)
G
gineshidalgo99 已提交
117
                       const WrapperStructOutput& wrapperStructOutput = WrapperStructOutput{});
G
gineshidalgo99 已提交
118

G
gineshidalgo99 已提交
119 120
        /**
         * Function to start multi-threading.
121 122
         * Similar to start(), but exec() blocks the thread that calls the function (it saves 1 thread). Use exec()
         * instead of start() if the calling thread will otherwise be waiting for the Wrapper to end.
G
gineshidalgo99 已提交
123
         */
G
gineshidalgo99 已提交
124 125
        void exec();

G
gineshidalgo99 已提交
126 127
        /**
         * Function to start multi-threading.
128 129 130 131 132 133
         * Similar to exec(), but start() does not block the thread that calls the function. It just opens new threads,
         * so it lets the user perform other tasks meanwhile on the calling thread.
         * VERY IMPORTANT NOTE: if the GUI is selected and OpenCV is compiled with Qt support, this option will not
         * work. Qt needs the main thread to plot visual results, so the final GUI (which uses OpenCV) would return an
         * exception similar to: `QMetaMethod::invoke: Unable to invoke methods with return values in queued
         * connections`. Use exec() in that case.
G
gineshidalgo99 已提交
134
         */
G
gineshidalgo99 已提交
135 136
        void start();

G
gineshidalgo99 已提交
137 138 139 140
        /**
         * Function to stop multi-threading.
         * It can be called internally or externally.
         */
G
gineshidalgo99 已提交
141 142
        void stop();

G
gineshidalgo99 已提交
143 144 145 146 147
        /**
         * Whether the Wrapper is running.
         * It will return true after exec() or start() and before stop(), and false otherwise.
         * @return Boolean specifying whether the Wrapper is running.
         */
G
gineshidalgo99 已提交
148 149
        bool isRunning() const;

G
gineshidalgo99 已提交
150 151 152 153 154 155 156
        /**
         * Emplace (move) an element on the first (input) queue.
         * Only valid if ThreadManagerMode::Asynchronous or ThreadManagerMode::AsynchronousIn.
         * If the input queue is full or the Wrapper was stopped, it will return false and not emplace it.
         * @param tDatums std::shared_ptr<TDatums> element to be emplaced.
         * @return Boolean specifying whether the tDatums could be emplaced.
         */
G
gineshidalgo99 已提交
157 158
        bool tryEmplace(std::shared_ptr<TDatums>& tDatums);

G
gineshidalgo99 已提交
159 160 161 162 163 164 165 166
        /**
         * Emplace (move) an element on the first (input) queue.
         * Similar to tryEmplace.
         * However, if the input queue is full, it will wait until it can emplace it.
         * If the Wrapper class is stopped before adding the element, it will return false and not emplace it.
         * @param tDatums std::shared_ptr<TDatums> element to be emplaced.
         * @return Boolean specifying whether the tDatums could be emplaced.
         */
G
gineshidalgo99 已提交
167 168
        bool waitAndEmplace(std::shared_ptr<TDatums>& tDatums);

G
gineshidalgo99 已提交
169 170 171 172 173 174
        /**
         * Push (copy) an element on the first (input) queue.
         * Same as tryEmplace, but it copies the data instead of moving it.
         * @param tDatums std::shared_ptr<TDatums> element to be pushed.
         * @return Boolean specifying whether the tDatums could be pushed.
         */
G
gineshidalgo99 已提交
175 176
        bool tryPush(const std::shared_ptr<TDatums>& tDatums);

G
gineshidalgo99 已提交
177 178 179 180 181 182
        /**
         * Push (copy) an element on the first (input) queue.
         * Same as waitAndEmplace, but it copies the data instead of moving it.
         * @param tDatums std::shared_ptr<TDatums> element to be pushed.
         * @return Boolean specifying whether the tDatums could be pushed.
         */
G
gineshidalgo99 已提交
183 184
        bool waitAndPush(const std::shared_ptr<TDatums>& tDatums);

G
gineshidalgo99 已提交
185 186 187 188 189 190 191
        /**
         * Pop (retrieve) an element from the last (output) queue.
         * Only valid if ThreadManagerMode::Asynchronous or ThreadManagerMode::AsynchronousOut.
         * If the output queue is empty or the Wrapper was stopped, it will return false and not retrieve it.
         * @param tDatums std::shared_ptr<TDatums> element where the retrieved element will be placed.
         * @return Boolean specifying whether the tDatums could be retrieved.
         */
G
gineshidalgo99 已提交
192 193
        bool tryPop(std::shared_ptr<TDatums>& tDatums);

G
gineshidalgo99 已提交
194 195 196 197 198 199 200 201
        /**
         * Pop (retrieve) an element from the last (output) queue.
         * Similar to tryPop.
         * However, if the output queue is empty, it will wait until it can pop an element.
         * If the Wrapper class is stopped before popping the element, it will return false and not retrieve it.
         * @param tDatums std::shared_ptr<TDatums> element where the retrieved element will be placed.
         * @return Boolean specifying whether the tDatums could be retrieved.
         */
G
gineshidalgo99 已提交
202 203 204
        bool waitAndPop(std::shared_ptr<TDatums>& tDatums);

    private:
G
gineshidalgo99 已提交
205
        const ThreadManagerMode mThreadManagerMode;
G
gineshidalgo99 已提交
206
        const std::shared_ptr<std::pair<std::atomic<bool>, std::atomic<int>>> spVideoSeek;
207
        bool mConfigured;
G
gineshidalgo99 已提交
208 209 210 211
        ThreadManager<std::shared_ptr<TDatums>> mThreadManager;
        bool mUserInputWsOnNewThread;
        bool mUserPostProcessingWsOnNewThread;
        bool mUserOutputWsOnNewThread;
G
gineshidalgo99 已提交
212
        unsigned long long mThreadId;
G
gineshidalgo99 已提交
213
        bool mMultiThreadEnabled;
G
gineshidalgo99 已提交
214 215 216 217
        // Workers
        std::vector<TWorker> mUserInputWs;
        TWorker wDatumProducer;
        TWorker spWIdGenerator;
218
        TWorker spWScaleAndSizeExtractor;
G
gineshidalgo99 已提交
219 220 221 222 223 224 225 226 227
        TWorker spWCvMatToOpInput;
        TWorker spWCvMatToOpOutput;
        std::vector<std::vector<TWorker>> spWPoses;
        std::vector<TWorker> mPostProcessingWs;
        std::vector<TWorker> mUserPostProcessingWs;
        std::vector<TWorker> mOutputWs;
        TWorker spWGui;
        std::vector<TWorker> mUserOutputWs;

G
gineshidalgo99 已提交
228 229
        /**
         * Frees TWorker variables (private internal function).
230 231
         * For most cases, this class is non-necessary, since std::shared_ptr are automatically cleaned on destruction
         * of each class.
G
gineshidalgo99 已提交
232 233 234 235 236 237
         * However, it might be useful if the same Wrapper is gonna be started twice (not recommended on most cases).
         */
        void reset();

        /**
         * Set ThreadManager from TWorkers (private internal function).
238 239
         * After any configure() has been called, the TWorkers are initialized. This function resets the ThreadManager
         * and adds them.
G
gineshidalgo99 已提交
240 241
         * Common code for start() and exec().
         */
G
gineshidalgo99 已提交
242 243
        void configureThreadManager();

G
gineshidalgo99 已提交
244 245 246 247 248 249 250
        /**
         * Thread ID increase (private internal function).
         * If multi-threading mode, it increases the thread ID.
         * If single-threading mode (for debugging), it does not modify it.
         * Note that mThreadId must be re-initialized to 0 before starting a new Wrapper configuration.
         * @return unsigned int with the next thread id value.
         */
251
        unsigned long long threadIdPP();
G
gineshidalgo99 已提交
252 253 254 255 256 257 258 259 260 261

        DELETE_COPY(Wrapper);
    };
}





// Implementation
G
Gines Hidalgo 已提交
262
#include <openpose/core/headers.hpp>
263
#include <openpose/face/headers.hpp>
G
Gines Hidalgo 已提交
264 265
#include <openpose/filestream/headers.hpp>
#include <openpose/gui/headers.hpp>
266
#include <openpose/hand/headers.hpp>
G
Gines Hidalgo 已提交
267 268
#include <openpose/pose/headers.hpp>
#include <openpose/producer/headers.hpp>
G
gineshidalgo99 已提交
269
#include <openpose/experimental/tracking/headers.hpp>
270
#include <openpose/utilities/cuda.hpp>
G
Gines Hidalgo 已提交
271
#include <openpose/utilities/fileSystem.hpp>
G
gineshidalgo99 已提交
272
#include <openpose/utilities/standard.hpp>
G
gineshidalgo99 已提交
273 274 275
namespace op
{
    template<typename TDatums, typename TWorker, typename TQueue>
G
gineshidalgo99 已提交
276 277
    Wrapper<TDatums, TWorker, TQueue>::Wrapper(const ThreadManagerMode threadManagerMode) :
        mThreadManagerMode{threadManagerMode},
G
gineshidalgo99 已提交
278
        spVideoSeek{std::make_shared<std::pair<std::atomic<bool>, std::atomic<int>>>()},
279
        mConfigured{false},
G
gineshidalgo99 已提交
280 281
        mThreadManager{threadManagerMode},
        mMultiThreadEnabled{true}
G
gineshidalgo99 已提交
282 283 284
    {
        try
        {
285
            // It cannot be directly included in the constructor (compiler error for copying std::atomic)
G
gineshidalgo99 已提交
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
            spVideoSeek->first = false;
            spVideoSeek->second = 0;
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    Wrapper<TDatums, TWorker, TQueue>::~Wrapper()
    {
        try
        {
            stop();
            reset();
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
G
gineshidalgo99 已提交
310
    void Wrapper<TDatums, TWorker, TQueue>::disableMultiThreading()
G
gineshidalgo99 已提交
311 312 313
    {
        try
        {
G
gineshidalgo99 已提交
314
            mMultiThreadEnabled = false;
G
gineshidalgo99 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    void Wrapper<TDatums, TWorker, TQueue>::setWorkerInput(const TWorker& worker, const bool workerOnNewThread)
    {
        try
        {
            mUserInputWs.clear();
            if (worker == nullptr)
                error("Your worker is a nullptr.", __LINE__, __FILE__, __FUNCTION__);
            mUserInputWs.emplace_back(worker);
            mUserInputWsOnNewThread = {workerOnNewThread};
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
340 341
    void Wrapper<TDatums, TWorker, TQueue>::setWorkerPostProcessing(const TWorker& worker,
                                                                    const bool workerOnNewThread)
G
gineshidalgo99 已提交
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
    {
        try
        {
            mUserPostProcessingWs.clear();
            if (worker == nullptr)
                error("Your worker is a nullptr.", __LINE__, __FILE__, __FUNCTION__);
            mUserPostProcessingWs.emplace_back(worker);
            mUserPostProcessingWsOnNewThread = {workerOnNewThread};
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    void Wrapper<TDatums, TWorker, TQueue>::setWorkerOutput(const TWorker& worker, const bool workerOnNewThread)
    {
        try
        {
            mUserOutputWs.clear();
            if (worker == nullptr)
                error("Your worker is a nullptr.", __LINE__, __FILE__, __FUNCTION__);
            mUserOutputWs.emplace_back(worker);
            mUserOutputWsOnNewThread = {workerOnNewThread};
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
G
gineshidalgo99 已提交
375 376
    void Wrapper<TDatums, TWorker, TQueue>::configure(const WrapperStructPose& wrapperStructPose,
                                                      const WrapperStructInput& wrapperStructInput,
G
gineshidalgo99 已提交
377
                                                      const WrapperStructOutput& wrapperStructOutput)
G
gineshidalgo99 已提交
378 379 380
    {
        try
        {
381
            configure(wrapperStructPose, WrapperStructFace{}, WrapperStructHand{},
G
gineshidalgo99 已提交
382
                      wrapperStructInput, wrapperStructOutput);
G
gineshidalgo99 已提交
383 384 385 386 387 388 389 390
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
G
gineshidalgo99 已提交
391 392 393 394
    void Wrapper<TDatums, TWorker, TQueue>::configure(const WrapperStructPose& wrapperStructPose,
                                                      const WrapperStructFace& wrapperStructFace,
                                                      const WrapperStructInput& wrapperStructInput,
                                                      const WrapperStructOutput& wrapperStructOutput)
395 396 397
    {
        try
        {
398
            configure(wrapperStructPose, wrapperStructFace, WrapperStructHand{},
G
gineshidalgo99 已提交
399
                      wrapperStructInput, wrapperStructOutput);
400 401 402 403 404 405 406 407
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
G
gineshidalgo99 已提交
408
    void Wrapper<TDatums, TWorker, TQueue>::configure(const WrapperStructPose& wrapperStructPose,
409
                                                      const WrapperStructHand& wrapperStructHand,
G
gineshidalgo99 已提交
410 411
                                                      const WrapperStructInput& wrapperStructInput,
                                                      const WrapperStructOutput& wrapperStructOutput)
412 413 414
    {
        try
        {
415
            configure(wrapperStructPose, WrapperStructFace{}, wrapperStructHand,
G
gineshidalgo99 已提交
416
                      wrapperStructInput, wrapperStructOutput);
417 418 419 420 421 422 423 424
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
G
gineshidalgo99 已提交
425 426
    void Wrapper<TDatums, TWorker, TQueue>::configure(const WrapperStructPose& wrapperStructPose,
                                                      const WrapperStructFace& wrapperStructFace,
427
                                                      const WrapperStructHand& wrapperStructHand,
G
gineshidalgo99 已提交
428
                                                      const WrapperStructInput& wrapperStructInput,
429
                                                      const WrapperStructOutput& wrapperStructOutput)
G
gineshidalgo99 已提交
430 431 432 433 434 435 436 437
    {
        try
        {
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);

            // Shortcut
            typedef std::shared_ptr<TDatums> TDatumsPtr;

438
            // Required parameters
439 440
            const auto renderOutput = wrapperStructPose.renderMode != RenderMode::None
                                        || wrapperStructFace.renderMode != RenderMode::None
441
                                        || wrapperStructHand.renderMode != RenderMode::None;
442 443 444
            const auto renderOutputGpu = wrapperStructPose.renderMode == RenderMode::Gpu
                                            || wrapperStructFace.renderMode == RenderMode::Gpu
                                            || wrapperStructHand.renderMode == RenderMode::Gpu;
G
gineshidalgo99 已提交
445
            const auto renderFace = wrapperStructFace.enable && wrapperStructFace.renderMode != RenderMode::None;
446 447
            const auto renderHand = wrapperStructHand.enable && wrapperStructHand.renderMode != RenderMode::None;
            const auto renderHandGpu = wrapperStructHand.enable && wrapperStructHand.renderMode == RenderMode::Gpu;
448 449 450

            // Check no wrong/contradictory flags enabled
            if (wrapperStructPose.alphaKeypoint < 0. || wrapperStructPose.alphaKeypoint > 1.
451 452
                || wrapperStructFace.alphaHeatMap < 0. || wrapperStructFace.alphaHeatMap > 1.
                || wrapperStructHand.alphaHeatMap < 0. || wrapperStructHand.alphaHeatMap > 1.)
G
gineshidalgo99 已提交
453
                error("Alpha value for blending must be in the range [0,1].", __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
454
            if (wrapperStructPose.scaleGap <= 0.f && wrapperStructPose.scalesNumber > 1)
455 456
                error("The scale gap must be greater than 0 (it has no effect if the number of scales is 1).",
                      __LINE__, __FUNCTION__, __FILE__);
457
            if (!renderOutput && (!wrapperStructOutput.writeImages.empty() || !wrapperStructOutput.writeVideo.empty()))
G
gineshidalgo99 已提交
458
            {
459 460
                const auto message = "In order to save the rendered frames (`--write_images` or `--write_video`), you"
                                     " cannot disable `--render_pose`.";
461
                log(message, Priority::High);
G
gineshidalgo99 已提交
462 463
            }
            if (!wrapperStructOutput.writeHeatMaps.empty() && wrapperStructPose.heatMapTypes.empty())
G
gineshidalgo99 已提交
464
            {
465 466
                const auto message = "In order to save the heatmaps (`--write_heatmaps`), you need to pick which heat"
                                     " maps you want to save: `--heatmaps_add_X` flags or fill the"
467
                                     " wrapperStructPose.heatMapTypes.";
G
gineshidalgo99 已提交
468 469
                error(message, __LINE__, __FUNCTION__, __FILE__);
            }
470
            if (!wrapperStructOutput.writeHeatMaps.empty()
G
gineshidalgo99 已提交
471 472
                && (wrapperStructPose.heatMapScale != ScaleMode::UnsignedChar &&
                        wrapperStructOutput.writeHeatMapsFormat != "float"))
G
gineshidalgo99 已提交
473
            {
G
gineshidalgo99 已提交
474 475
                const auto message = "In order to save the heatmaps, you must either set"
                                     " wrapperStructPose.heatMapScale to ScaleMode::UnsignedChar (i.e. range [0, 255])"
476
                                     " or `--write_heatmaps_format` to `float` to storage floating numbers in binary"
G
gineshidalgo99 已提交
477
                                     " mode.";
G
gineshidalgo99 已提交
478 479
                error(message, __LINE__, __FUNCTION__, __FILE__);
            }
480 481
            if (mUserOutputWs.empty() && mThreadManagerMode != ThreadManagerMode::Asynchronous
                && mThreadManagerMode != ThreadManagerMode::AsynchronousOut)
G
gineshidalgo99 已提交
482
            {
483 484 485 486 487 488
                const std::string additionalMessage{
                    " You could also set mThreadManagerMode = mThreadManagerMode::Asynchronous(Out) and/or add your"
                    " own output worker class before calling this function."
                };
                const auto savingSomething = (
                    !wrapperStructOutput.writeImages.empty() || !wrapperStructOutput.writeVideo.empty()
489
                        || !wrapperStructOutput.writeKeypoint.empty() || !wrapperStructOutput.writeJson.empty()
490 491
                        || !wrapperStructOutput.writeCocoJson.empty() || !wrapperStructOutput.writeHeatMaps.empty()
                );
G
gineshidalgo99 已提交
492
                if (!wrapperStructOutput.displayGui && !savingSomething)
G
gineshidalgo99 已提交
493
                {
494 495
                    const auto message = "No output is selected (`--no_display`) and no results are generated (no"
                                         " `--write_X` flags enabled). Thus, no output would be generated."
496
                                         + additionalMessage;
G
gineshidalgo99 已提交
497 498
                    error(message, __LINE__, __FUNCTION__, __FILE__);
                }
G
gineshidalgo99 已提交
499
                if (wrapperStructInput.framesRepeat && savingSomething)
G
gineshidalgo99 已提交
500
                {
501 502
                    const auto message = "Frames repetition (`--frames_repeat`) is enabled as well as some writing"
                                         " function (`--write_X`). This program would never stop recording the same"
503
                                         " frames over and over. Please, disable repetition or remove writing.";
G
gineshidalgo99 已提交
504 505
                    error(message, __LINE__, __FUNCTION__, __FILE__);
                }
506 507 508
                // Warnings
                if ((wrapperStructOutput.displayGui && wrapperStructOutput.guiVerbose) && !renderOutput)
                {
509 510 511 512
                    const auto message = "No render is enabled (e.g. `--render_pose 0`), so you might also want to"
                                         " remove the display (set `--no_display` or `--no_gui_verbose`). If you"
                                         " simply want to use OpenPose to record video/images without keypoints, you"
                                         " only need to set `--num_gpu 0`." + additionalMessage;
513 514
                    log(message, Priority::High);
                }
G
gineshidalgo99 已提交
515
                if (wrapperStructInput.realTimeProcessing && savingSomething)
G
gineshidalgo99 已提交
516
                {
517 518 519
                    const auto message = "Real time processing is enabled as well as some writing function. Thus, some"
                                         " frames might be skipped. Consider disabling real time processing if you"
                                         " intend to save any results.";
520
                    log(message, Priority::High);
G
gineshidalgo99 已提交
521 522
                }
            }
G
gineshidalgo99 已提交
523
            if (!wrapperStructOutput.writeVideo.empty() && wrapperStructInput.producerSharedPtr == nullptr)
524 525
                error("Writting video is only available if the OpenPose producer is used (i.e."
                      " wrapperStructInput.producerSharedPtr cannot be a nullptr).", __LINE__, __FUNCTION__, __FILE__);
D
Donglai Xiang 已提交
526 527 528 529 530 531 532 533
            if (!wrapperStructPose.enable)
            {
                if (!wrapperStructFace.enable)
                    error("Body keypoint detection must be enabled.", __LINE__, __FUNCTION__, __FILE__);
                if (wrapperStructHand.enable)
                    error("Body keypoint detection must be enabled in order to run hand keypoint detection.",
                          __LINE__, __FUNCTION__, __FILE__);
            }
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
            #ifdef CPU_ONLY
                if (wrapperStructPose.gpuNumber > 0)
                    error("GPU number must be negative or 0 if CPU_ONLY is enabled.", __LINE__, __FUNCTION__, __FILE__);
            #endif

            // Get number threads
            // CPU --> 1 thread or no pose extraction
            #ifdef CPU_ONLY
                const auto numberThreads = (wrapperStructPose.gpuNumber == 0 ? 0 : 1);
                const auto gpuNumberStart = 0;
            // GPU --> user picks (<= #GPUs)
            #else
                auto numberThreads = wrapperStructPose.gpuNumber;
                const auto gpuNumberStart = wrapperStructPose.gpuNumberStart;
                // If number GPU < 0 --> set it to all the available GPUs
                if (numberThreads < 0)
                {
                    // Get total number GPUs
                    const auto totalGpuNumber = getGpuNumber();
                    if (totalGpuNumber <= gpuNumberStart)
                        error("Number of initial GPUs (`--number_gpu_start`) must be lower than the total number of used"
                              " GPUs (`--number_gpu`)", __LINE__, __FUNCTION__, __FILE__);
                    numberThreads = totalGpuNumber - gpuNumberStart;
                    // Reset initial GPU to 0 (we want them all)
                    // Logging message
                    log("Auto-detecting all available GPUs... Detected " + std::to_string(totalGpuNumber)
                        + " GPU(s), using " + std::to_string(numberThreads) + " of them starting at GPU "
                        + std::to_string(gpuNumberStart) + ".", Priority::High);
                }
            #endif
G
gineshidalgo99 已提交
564 565

            // Proper format
G
gineshidalgo99 已提交
566
            const auto writeImagesCleaned = formatAsDirectory(wrapperStructOutput.writeImages);
567
            const auto writeKeypointCleaned = formatAsDirectory(wrapperStructOutput.writeKeypoint);
568
            const auto writeJsonCleaned = formatAsDirectory(wrapperStructOutput.writeJson);
G
gineshidalgo99 已提交
569
            const auto writeHeatMapsCleaned = formatAsDirectory(wrapperStructOutput.writeHeatMaps);
D
Donglai Xiang 已提交
570
            const auto modelFolder = formatAsDirectory(wrapperStructPose.modelFolder);
G
gineshidalgo99 已提交
571 572

            // Common parameters
G
gineshidalgo99 已提交
573
            auto finalOutputSize = wrapperStructPose.outputSize;
574
            Point<int> producerSize{-1,-1};
G
gineshidalgo99 已提交
575
            if (wrapperStructInput.producerSharedPtr != nullptr)
G
gineshidalgo99 已提交
576 577
            {
                // 1. Set producer properties
578 579
                const auto displayProducerFpsMode = (wrapperStructInput.realTimeProcessing
                                                      ? ProducerFpsMode::OriginalFps : ProducerFpsMode::RetrievalFps);
G
gineshidalgo99 已提交
580 581 582
                wrapperStructInput.producerSharedPtr->setProducerFpsMode(displayProducerFpsMode);
                wrapperStructInput.producerSharedPtr->set(ProducerProperty::Flip, wrapperStructInput.frameFlip);
                wrapperStructInput.producerSharedPtr->set(ProducerProperty::Rotation, wrapperStructInput.frameRotate);
583 584
                wrapperStructInput.producerSharedPtr->set(ProducerProperty::AutoRepeat,
                                                          wrapperStructInput.framesRepeat);
G
gineshidalgo99 已提交
585
                // 2. Set finalOutputSize
586
                producerSize = Point<int>{(int)wrapperStructInput.producerSharedPtr->get(CV_CAP_PROP_FRAME_WIDTH),
G
gineshidalgo99 已提交
587
                                          (int)wrapperStructInput.producerSharedPtr->get(CV_CAP_PROP_FRAME_HEIGHT)};
588 589 590
                // Set finalOutputSize to input size if desired
                if (finalOutputSize.x == -1 || finalOutputSize.y == -1)
                    finalOutputSize = producerSize;
G
gineshidalgo99 已提交
591
            }
G
gineshidalgo99 已提交
592 593

            // Producer
G
gineshidalgo99 已提交
594
            if (wrapperStructInput.producerSharedPtr != nullptr)
G
gineshidalgo99 已提交
595
            {
G
gineshidalgo99 已提交
596
                const auto datumProducer = std::make_shared<DatumProducer<TDatums>>(
597 598
                    wrapperStructInput.producerSharedPtr, wrapperStructInput.frameFirst, wrapperStructInput.frameLast,
                    spVideoSeek
G
gineshidalgo99 已提交
599
                );
G
gineshidalgo99 已提交
600 601 602 603 604 605
                wDatumProducer = std::make_shared<WDatumProducer<TDatumsPtr, TDatums>>(datumProducer);
            }
            else
                wDatumProducer = nullptr;

            std::vector<std::shared_ptr<PoseExtractor>> poseExtractors;
606 607
            std::vector<std::shared_ptr<PoseGpuRenderer>> poseGpuRenderers;
            std::shared_ptr<PoseCpuRenderer> poseCpuRenderer;
608
            if (numberThreads > 0)
G
gineshidalgo99 已提交
609
            {
610 611 612 613 614 615 616 617 618 619 620
                // Get input scales and sizes
                const auto scaleAndSizeExtractor = std::make_shared<ScaleAndSizeExtractor>(
                    wrapperStructPose.netInputSize, finalOutputSize, wrapperStructPose.scalesNumber,
                    wrapperStructPose.scaleGap
                );
                spWScaleAndSizeExtractor = std::make_shared<WScaleAndSizeExtractor<TDatumsPtr>>(scaleAndSizeExtractor);

                // Input cvMat to OpenPose input & output format
                const auto cvMatToOpInput = std::make_shared<CvMatToOpInput>();
                spWCvMatToOpInput = std::make_shared<WCvMatToOpInput<TDatumsPtr>>(cvMatToOpInput);
                if (renderOutput)
G
gineshidalgo99 已提交
621
                {
622 623 624 625 626 627 628
                    const auto cvMatToOpOutput = std::make_shared<CvMatToOpOutput>();
                    spWCvMatToOpOutput = std::make_shared<WCvMatToOpOutput<TDatumsPtr>>(cvMatToOpOutput);
                }

                // Pose estimators & renderers
                std::vector<TWorker> cpuRenderers;
                spWPoses.clear();
629
                spWPoses.resize(numberThreads);
630 631 632
                if (wrapperStructPose.enable)
                {
                    // Pose estimators
633
                    for (auto gpuId = 0; gpuId < numberThreads; gpuId++)
634 635 636
                        poseExtractors.emplace_back(std::make_shared<PoseExtractorCaffe>(
                            wrapperStructPose.poseModel, modelFolder, gpuId + gpuNumberStart,
                            wrapperStructPose.heatMapTypes, wrapperStructPose.heatMapScale,
637
                            wrapperStructPose.addPartCandidates, wrapperStructPose.enableGoogleLogging
638 639 640 641
                        ));

                    // Pose renderers
                    if (renderOutputGpu || wrapperStructPose.renderMode == RenderMode::Cpu)
G
gineshidalgo99 已提交
642
                    {
643 644 645 646 647 648 649 650
                        // If wrapperStructPose.renderMode != RenderMode::Gpu but renderOutput, then we create an
                        // alpha = 0 pose renderer in order to keep the removing background option
                        const auto alphaKeypoint = (wrapperStructPose.renderMode != RenderMode::None
                                                    ? wrapperStructPose.alphaKeypoint : 0.f);
                        const auto alphaHeatMap = (wrapperStructPose.renderMode != RenderMode::None
                                                    ? wrapperStructPose.alphaHeatMap : 0.f);
                        // GPU rendering
                        if (renderOutputGpu)
D
Donglai Xiang 已提交
651
                        {
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
                            for (const auto& poseExtractor : poseExtractors)
                            {
                                poseGpuRenderers.emplace_back(std::make_shared<PoseGpuRenderer>(
                                    wrapperStructPose.poseModel, poseExtractor, wrapperStructPose.renderThreshold,
                                    wrapperStructPose.blendOriginalFrame, alphaKeypoint,
                                    alphaHeatMap, wrapperStructPose.defaultPartToRender
                                ));
                            }
                        }
                        // CPU rendering
                        if (wrapperStructPose.renderMode == RenderMode::Cpu)
                        {
                            poseCpuRenderer = std::make_shared<PoseCpuRenderer>(wrapperStructPose.poseModel,
                                                                                wrapperStructPose.renderThreshold,
                                                                                wrapperStructPose.blendOriginalFrame);
                            cpuRenderers.emplace_back(std::make_shared<WPoseRenderer<TDatumsPtr>>(poseCpuRenderer));
D
Donglai Xiang 已提交
668 669
                        }
                    }
670
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
671

672 673 674 675 676
                    // Pose extractor(s)
                    spWPoses.resize(poseExtractors.size());
                    for (auto i = 0u; i < spWPoses.size(); i++)
                        spWPoses.at(i) = {std::make_shared<WPoseExtractor<TDatumsPtr>>(poseExtractors.at(i))};
                }
D
Donglai Xiang 已提交
677

G
gineshidalgo99 已提交
678

679 680
                // Face extractor(s)
                if (wrapperStructFace.enable)
D
Donglai Xiang 已提交
681
                {
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
                    // Face detector
                    // OpenPose face detector
                    if (wrapperStructPose.enable)
                    {
                        const auto faceDetector = std::make_shared<FaceDetector>(wrapperStructPose.poseModel);
                        for (auto gpu = 0u; gpu < spWPoses.size(); gpu++)
                            spWPoses.at(gpu).emplace_back(std::make_shared<WFaceDetector<TDatumsPtr>>(faceDetector));
                    }
                    // OpenCV face detector
                    else
                    {
                        log("Body keypoint detection is disabled. Hence, using OpenCV face detector (much less"
                            " accurate but faster).", Priority::High);
                        for (auto gpu = 0u; gpu < spWPoses.size(); gpu++)
                        {
                            // 1 FaceDetectorOpenCV per thread, OpenCV face detector is not thread-safe
                            const auto faceDetectorOpenCV = std::make_shared<FaceDetectorOpenCV>(modelFolder);
                            spWPoses.at(gpu).emplace_back(
                                std::make_shared<WFaceDetectorOpenCV<TDatumsPtr>>(faceDetectorOpenCV)
                            );
                        }
                    }
                    // Face keypoint extractor
D
Donglai Xiang 已提交
705 706
                    for (auto gpu = 0u; gpu < spWPoses.size(); gpu++)
                    {
707 708 709 710 711 712
                        // Face keypoint extractor
                        const auto netOutputSize = wrapperStructFace.netInputSize;
                        const auto faceExtractor = std::make_shared<FaceExtractorCaffe>(
                            wrapperStructFace.netInputSize, netOutputSize, modelFolder,
                            gpu + gpuNumberStart, wrapperStructPose.heatMapTypes, wrapperStructPose.heatMapScale,
                            wrapperStructPose.enableGoogleLogging
713
                        );
714
                        spWPoses.at(gpu).emplace_back(std::make_shared<WFaceExtractor<TDatumsPtr>>(faceExtractor));
D
Donglai Xiang 已提交
715 716
                    }
                }
717

718 719
                // Hand extractor(s)
                if (wrapperStructHand.enable)
G
gineshidalgo99 已提交
720
                {
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
                    const auto handDetector = std::make_shared<HandDetector>(wrapperStructPose.poseModel);
                    for (auto gpu = 0u; gpu < spWPoses.size(); gpu++)
                    {
                        // Hand detector
                        // If tracking
                        if (wrapperStructHand.tracking)
                            spWPoses.at(gpu).emplace_back(
                                std::make_shared<WHandDetectorTracking<TDatumsPtr>>(handDetector)
                            );
                        // If detection
                        else
                            spWPoses.at(gpu).emplace_back(std::make_shared<WHandDetector<TDatumsPtr>>(handDetector));
                        // Hand keypoint extractor
                        const auto netOutputSize = wrapperStructHand.netInputSize;
                        const auto handExtractor = std::make_shared<HandExtractorCaffe>(
                            wrapperStructHand.netInputSize, netOutputSize, modelFolder,
                            gpu + gpuNumberStart, wrapperStructHand.scalesNumber, wrapperStructHand.scaleRange,
                            wrapperStructPose.heatMapTypes, wrapperStructPose.heatMapScale,
                            wrapperStructPose.enableGoogleLogging
740
                        );
741 742 743 744 745 746 747 748 749
                        spWPoses.at(gpu).emplace_back(
                            std::make_shared<WHandExtractor<TDatumsPtr>>(handExtractor)
                            );
                        // If tracking
                        if (wrapperStructHand.tracking)
                            spWPoses.at(gpu).emplace_back(
                                std::make_shared<WHandDetectorUpdate<TDatumsPtr>>(handDetector)
                            );
                    }
G
gineshidalgo99 已提交
750 751
                }

752 753 754 755 756 757
                // Pose renderer(s)
                if (!poseGpuRenderers.empty())
                    for (auto i = 0u; i < spWPoses.size(); i++)
                        spWPoses.at(i).emplace_back(std::make_shared<WPoseRenderer<TDatumsPtr>>(
                            poseGpuRenderers.at(i)
                        ));
G
gineshidalgo99 已提交
758

759 760
                // Face renderer(s)
                if (renderFace)
G
gineshidalgo99 已提交
761
                {
762 763
                    // CPU rendering
                    if (wrapperStructFace.renderMode == RenderMode::Cpu)
764
                    {
G
gineshidalgo99 已提交
765
                        // Construct face renderer
766
                        const auto faceRenderer = std::make_shared<FaceCpuRenderer>(wrapperStructFace.renderThreshold,
767 768
                                                                                    wrapperStructFace.alphaKeypoint,
                                                                                    wrapperStructFace.alphaHeatMap);
769 770 771 772 773 774 775
                        // Add worker
                        cpuRenderers.emplace_back(std::make_shared<WFaceRenderer<TDatumsPtr>>(faceRenderer));
                    }
                    // GPU rendering
                    else if (wrapperStructFace.renderMode == RenderMode::Gpu)
                    {
                        for (auto i = 0u; i < spWPoses.size(); i++)
G
gineshidalgo99 已提交
776
                        {
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
                            // Construct face renderer
                            const auto faceRenderer = std::make_shared<FaceGpuRenderer>(
                                wrapperStructFace.renderThreshold, wrapperStructFace.alphaKeypoint,
                                wrapperStructFace.alphaHeatMap
                            );
                            // Performance boost -> share spGpuMemory for all renderers
                            if (!poseGpuRenderers.empty())
                            {
                                const bool isLastRenderer = !renderHandGpu;
                                const auto renderer = std::static_pointer_cast<PoseGpuRenderer>(
                                    poseGpuRenderers.at(i)
                                );
                                faceRenderer->setSharedParametersAndIfLast(renderer->getSharedParameters(),
                                                                           isLastRenderer);
                            }
                            // Add worker
                            spWPoses.at(i).emplace_back(std::make_shared<WFaceRenderer<TDatumsPtr>>(faceRenderer));
G
gineshidalgo99 已提交
794
                        }
795
                    }
796 797
                    else
                        error("Unknown RenderMode.", __LINE__, __FUNCTION__, __FILE__);
798 799
                }

800 801
                // Hand renderer(s)
                if (renderHand)
802
                {
803 804
                    // CPU rendering
                    if (wrapperStructHand.renderMode == RenderMode::Cpu)
805
                    {
806 807
                        // Construct hand renderer
                        const auto handRenderer = std::make_shared<HandCpuRenderer>(wrapperStructHand.renderThreshold,
808 809
                                                                                    wrapperStructHand.alphaKeypoint,
                                                                                    wrapperStructHand.alphaHeatMap);
810 811 812 813 814 815 816
                        // Add worker
                        cpuRenderers.emplace_back(std::make_shared<WHandRenderer<TDatumsPtr>>(handRenderer));
                    }
                    // GPU rendering
                    else if (wrapperStructHand.renderMode == RenderMode::Gpu)
                    {
                        for (auto i = 0u; i < spWPoses.size(); i++)
817
                        {
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
                            // Construct hands renderer
                            const auto handRenderer = std::make_shared<HandGpuRenderer>(
                                wrapperStructHand.renderThreshold, wrapperStructHand.alphaKeypoint,
                                wrapperStructHand.alphaHeatMap
                            );
                            // Performance boost -> share spGpuMemory for all renderers
                            if (!poseGpuRenderers.empty())
                            {
                                const bool isLastRenderer = true;
                                const auto renderer = std::static_pointer_cast<PoseGpuRenderer>(
                                    poseGpuRenderers.at(i)
                                    );
                                handRenderer->setSharedParametersAndIfLast(renderer->getSharedParameters(),
                                                                           isLastRenderer);
                            }
                            // Add worker
                            spWPoses.at(i).emplace_back(std::make_shared<WHandRenderer<TDatumsPtr>>(handRenderer));
835 836
                        }
                    }
837 838
                    else
                        error("Unknown RenderMode.", __LINE__, __FUNCTION__, __FILE__);
839
                }
G
gineshidalgo99 已提交
840

841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
                // Itermediate workers (e.g. OpenPose format to cv::Mat, json & frames recorder, ...)
                mPostProcessingWs.clear();
                // Frame buffer and ordering
                if (spWPoses.size() > 1u)
                    mPostProcessingWs.emplace_back(std::make_shared<WQueueOrderer<TDatumsPtr>>());
                // Person ID identification
                if (wrapperStructPose.identification)
                {
                    const auto personIdExtractor = std::make_shared<PersonIdExtractor>();
                    mPostProcessingWs.emplace_back(
                        std::make_shared<WPersonIdExtractor<TDatumsPtr>>(personIdExtractor)
                    );
                }
                // Frames processor (OpenPose format -> cv::Mat format)
                if (renderOutput)
                {
                    mPostProcessingWs = mergeVectors(mPostProcessingWs, cpuRenderers);
                    const auto opOutputToCvMat = std::make_shared<OpOutputToCvMat>();
                    mPostProcessingWs.emplace_back(std::make_shared<WOpOutputToCvMat<TDatumsPtr>>(opOutputToCvMat));
                }
                // Re-scale pose if desired
                // If desired scale is not the current input
                if (wrapperStructPose.keypointScale != ScaleMode::InputResolution
                    // and desired scale is not output when size(input) = size(output)
                    && !(wrapperStructPose.keypointScale == ScaleMode::OutputResolution &&
                         (finalOutputSize == producerSize || finalOutputSize.x <= 0 || finalOutputSize.y <= 0))
                    // and desired scale is not net output when size(input) = size(net output)
                    && !(wrapperStructPose.keypointScale == ScaleMode::NetOutputResolution
                         && producerSize == wrapperStructPose.netInputSize))
                {
                    // Then we must rescale the keypoints
                    auto keypointScaler = std::make_shared<KeypointScaler>(wrapperStructPose.keypointScale);
                    mPostProcessingWs.emplace_back(std::make_shared<WKeypointScaler<TDatumsPtr>>(keypointScaler));
                }
G
gineshidalgo99 已提交
875 876 877 878
            }

            mOutputWs.clear();
            // Write people pose data on disk (json for OpenCV >= 3, xml, yml...)
879
            if (!writeKeypointCleaned.empty())
G
gineshidalgo99 已提交
880
            {
881 882
                const auto keypointSaver = std::make_shared<KeypointSaver>(writeKeypointCleaned,
                                                                           wrapperStructOutput.writeKeypointFormat);
883 884 885
                mOutputWs.emplace_back(std::make_shared<WPoseSaver<TDatumsPtr>>(keypointSaver));
                if (wrapperStructFace.enable)
                    mOutputWs.emplace_back(std::make_shared<WFaceSaver<TDatumsPtr>>(keypointSaver));
886
                if (wrapperStructHand.enable)
887
                    mOutputWs.emplace_back(std::make_shared<WHandSaver<TDatumsPtr>>(keypointSaver));
G
gineshidalgo99 已提交
888
            }
889 890 891
            // Write OpenPose output data on disk in json format (body/hand/face keypoints, body part locations if
            // enabled, etc.)
            if (!writeJsonCleaned.empty())
G
gineshidalgo99 已提交
892
            {
893 894
                const auto peopleJsonSaver = std::make_shared<PeopleJsonSaver>(writeJsonCleaned);
                mOutputWs.emplace_back(std::make_shared<WPeopleJsonSaver<TDatumsPtr>>(peopleJsonSaver));
G
gineshidalgo99 已提交
895 896
            }
            // Write people pose data on disk (COCO validation json format)
G
gineshidalgo99 已提交
897
            if (!wrapperStructOutput.writeCocoJson.empty())
G
gineshidalgo99 已提交
898
            {
899 900 901 902
                // If humanFormat: bigger size (& maybe slower to process), but easier for user to read it
                const auto humanFormat = true;
                const auto cocoJsonSaver = std::make_shared<CocoJsonSaver>(wrapperStructOutput.writeCocoJson,
                                                                           humanFormat);
903
                mOutputWs.emplace_back(std::make_shared<WCocoJsonSaver<TDatumsPtr>>(cocoJsonSaver));
G
gineshidalgo99 已提交
904 905 906 907
            }
            // Write frames as desired image format on hard disk
            if (!writeImagesCleaned.empty())
            {
908 909
                const auto imageSaver = std::make_shared<ImageSaver>(writeImagesCleaned,
                                                                     wrapperStructOutput.writeImagesFormat);
G
gineshidalgo99 已提交
910 911 912
                mOutputWs.emplace_back(std::make_shared<WImageSaver<TDatumsPtr>>(imageSaver));
            }
            // Write frames as *.avi video on hard disk
G
gineshidalgo99 已提交
913
            if (!wrapperStructOutput.writeVideo.empty() && wrapperStructInput.producerSharedPtr != nullptr)
G
gineshidalgo99 已提交
914
            {
915
                if (finalOutputSize.x <= 0 || finalOutputSize.y <= 0)
916 917
                    error("Video can only be recorded if outputSize is fixed (e.g. video, webcam, IP camera),"
                          "but not for a image directory.", __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
918
                const auto originalVideoFps = (wrapperStructInput.producerSharedPtr->get(CV_CAP_PROP_FPS) > 0.
G
gineshidalgo99 已提交
919 920 921 922
                                               ? wrapperStructInput.producerSharedPtr->get(CV_CAP_PROP_FPS) : 30.);
                const auto videoSaver = std::make_shared<VideoSaver>(
                    wrapperStructOutput.writeVideo, CV_FOURCC('M','J','P','G'), originalVideoFps, finalOutputSize
                );
G
gineshidalgo99 已提交
923 924 925 926 927
                mOutputWs.emplace_back(std::make_shared<WVideoSaver<TDatumsPtr>>(videoSaver));
            }
            // Write heat maps as desired image format on hard disk
            if (!writeHeatMapsCleaned.empty())
            {
928 929
                const auto heatMapSaver = std::make_shared<HeatMapSaver>(writeHeatMapsCleaned,
                                                                         wrapperStructOutput.writeHeatMapsFormat);
G
gineshidalgo99 已提交
930 931 932
                mOutputWs.emplace_back(std::make_shared<WHeatMapSaver<TDatumsPtr>>(heatMapSaver));
            }
            // Add frame information for GUI
933 934
            // If this WGuiInfoAdder instance is placed before the WImageSaver or WVideoSaver, then the resulting
            // recorded frames will look exactly as the final displayed image by the GUI
935 936 937
            if (wrapperStructOutput.guiVerbose && (wrapperStructOutput.displayGui || !mUserOutputWs.empty()
                                                   || mThreadManagerMode == ThreadManagerMode::Asynchronous
                                                   || mThreadManagerMode == ThreadManagerMode::AsynchronousOut))
G
gineshidalgo99 已提交
938
            {
939
                const auto guiInfoAdder = std::make_shared<GuiInfoAdder>(numberThreads, wrapperStructOutput.displayGui);
G
gineshidalgo99 已提交
940 941 942 943
                mOutputWs.emplace_back(std::make_shared<WGuiInfoAdder<TDatumsPtr>>(guiInfoAdder));
            }
            // Minimal graphical user interface (GUI)
            spWGui = nullptr;
G
gineshidalgo99 已提交
944
            if (wrapperStructOutput.displayGui)
G
gineshidalgo99 已提交
945
            {
946 947 948 949 950 951 952 953
                // PoseRenderers to Renderers
                std::vector<std::shared_ptr<Renderer>> renderers;
                if (wrapperStructPose.renderMode == RenderMode::Cpu)
                    renderers.emplace_back(std::static_pointer_cast<Renderer>(poseCpuRenderer));
                else
                    for (const auto& poseGpuRenderer : poseGpuRenderers)
                        renderers.emplace_back(std::static_pointer_cast<Renderer>(poseGpuRenderer));
                // Gui
G
gineshidalgo99 已提交
954
                const auto gui = std::make_shared<Gui>(
955 956
                    finalOutputSize, wrapperStructOutput.fullScreen, mThreadManager.getIsRunningSharedPtr(),
                    spVideoSeek, poseExtractors, renderers
G
gineshidalgo99 已提交
957
                );
958
                // WGui
G
gineshidalgo99 已提交
959 960
                spWGui = {std::make_shared<WGui<TDatumsPtr>>(gui)};
            }
961 962
            // Set wrapper as configured
            mConfigured = true;
G
gineshidalgo99 已提交
963 964 965 966 967 968 969 970 971 972 973 974 975 976
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    void Wrapper<TDatums, TWorker, TQueue>::exec()
    {
        try
        {
            configureThreadManager();
977
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
978 979 980 981 982 983 984 985 986 987 988 989 990 991
            mThreadManager.exec();
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    void Wrapper<TDatums, TWorker, TQueue>::start()
    {
        try
        {
            configureThreadManager();
992
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
            mThreadManager.start();
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    void Wrapper<TDatums, TWorker, TQueue>::stop()
    {
        try
        {
            mThreadManager.stop();
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    bool Wrapper<TDatums, TWorker, TQueue>::isRunning() const
    {
        try
        {
            return mThreadManager.isRunning();
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            return false;
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    bool Wrapper<TDatums, TWorker, TQueue>::tryEmplace(std::shared_ptr<TDatums>& tDatums)
    {
        try
        {
            if (!mUserInputWs.empty())
1034 1035
                error("Emplace cannot be called if an input worker was already selected.",
                      __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
            return mThreadManager.tryEmplace(tDatums);
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            return false;
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    bool Wrapper<TDatums, TWorker, TQueue>::waitAndEmplace(std::shared_ptr<TDatums>& tDatums)
    {
        try
        {
            if (!mUserInputWs.empty())
1051 1052
                error("Emplace cannot be called if an input worker was already selected.",
                      __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
            return mThreadManager.waitAndEmplace(tDatums);
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            return false;
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    bool Wrapper<TDatums, TWorker, TQueue>::tryPush(const std::shared_ptr<TDatums>& tDatums)
    {
        try
        {
            if (!mUserInputWs.empty())
1068 1069
                error("Push cannot be called if an input worker was already selected.",
                      __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
            return mThreadManager.tryPush(tDatums);
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            return false;
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    bool Wrapper<TDatums, TWorker, TQueue>::waitAndPush(const std::shared_ptr<TDatums>& tDatums)
    {
        try
        {
            if (!mUserInputWs.empty())
1085 1086
                error("Push cannot be called if an input worker was already selected.",
                      __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
            return mThreadManager.waitAndPush(tDatums);
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            return false;
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    bool Wrapper<TDatums, TWorker, TQueue>::tryPop(std::shared_ptr<TDatums>& tDatums)
    {
        try
        {
            if (!mUserOutputWs.empty())
1102 1103
                error("Pop cannot be called if an output worker was already selected.",
                      __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
            return mThreadManager.tryPop(tDatums);
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            return false;
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
    bool Wrapper<TDatums, TWorker, TQueue>::waitAndPop(std::shared_ptr<TDatums>& tDatums)
    {
        try
        {
            if (!mUserOutputWs.empty())
1119 1120
                error("Pop cannot be called if an output worker was already selected.",
                      __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
1121 1122 1123 1124 1125 1126 1127 1128 1129
            return mThreadManager.waitAndPop(tDatums);
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
            return false;
        }
    }

G
gineshidalgo99 已提交
1130 1131 1132 1133 1134
    template<typename TDatums, typename TWorker, typename TQueue>
    void Wrapper<TDatums, TWorker, TQueue>::reset()
    {
        try
        {
1135
            mConfigured = false;
G
gineshidalgo99 已提交
1136 1137
            mThreadManager.reset();
            mThreadId = 0ull;
1138
            // Reset
G
gineshidalgo99 已提交
1139 1140
            mUserInputWs.clear();
            wDatumProducer = nullptr;
1141
            spWScaleAndSizeExtractor = nullptr;
G
gineshidalgo99 已提交
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
            spWCvMatToOpInput = nullptr;
            spWCvMatToOpOutput = nullptr;
            spWPoses.clear();
            mPostProcessingWs.clear();
            mUserPostProcessingWs.clear();
            mOutputWs.clear();
            spWGui = nullptr;
            mUserOutputWs.clear();
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

G
gineshidalgo99 已提交
1157 1158 1159 1160 1161 1162 1163 1164
    template<typename TDatums, typename TWorker, typename TQueue>
    void Wrapper<TDatums, TWorker, TQueue>::configureThreadManager()
    {
        try
        {
            // The less number of queues -> the less lag

            // Security checks
1165
            if (!mConfigured)
G
gineshidalgo99 已提交
1166
                error("Configure the Wrapper class before calling `start()`.", __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
1167
            if ((wDatumProducer == nullptr) == (mUserInputWs.empty())
1168 1169
                && mThreadManagerMode != ThreadManagerMode::Asynchronous
                && mThreadManagerMode != ThreadManagerMode::AsynchronousIn)
G
gineshidalgo99 已提交
1170
            {
1171 1172 1173
                const auto message = "You need to have 1 and only 1 producer selected. You can introduce your own"
                                     " producer by using setWorkerInput() or use the OpenPose default producer by"
                                     " configuring it in the configure function) or use the"
G
gineshidalgo99 已提交
1174 1175 1176
                                     " ThreadManagerMode::Asynchronous(In) mode.";
                error(message, __LINE__, __FUNCTION__, __FILE__);
            }
1177 1178
            if (mOutputWs.empty() && mUserOutputWs.empty() && spWGui == nullptr
                && mThreadManagerMode != ThreadManagerMode::Asynchronous
G
gineshidalgo99 已提交
1179 1180
                && mThreadManagerMode != ThreadManagerMode::AsynchronousOut)
            {
G
gineshidalgo99 已提交
1181
                error("No output selected.", __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
1182
            }
G
gineshidalgo99 已提交
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193

            // Thread Manager:
            // Clean previous thread manager (avoid configure to crash the program if used more than once)
            mThreadManager.reset();
            mThreadId = 0ull;
            auto queueIn = 0ull;
            auto queueOut = 1ull;
            // If custom user Worker and uses its own thread
            spWIdGenerator = std::make_shared<WIdGenerator<std::shared_ptr<TDatums>>>();
            if (!mUserInputWs.empty() && mUserInputWsOnNewThread)
            {
1194 1195
                // Thread 0, queues 0 -> 1
                mThreadManager.add(mThreadId, mUserInputWs, queueIn++, queueOut++);
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
                if (spWScaleAndSizeExtractor != nullptr && spWCvMatToOpInput != nullptr)
                {
                    threadIdPP();
                    // Thread 1, queues 1 -> 2
                    if (spWCvMatToOpOutput == nullptr)
                        mThreadManager.add(mThreadId, {spWIdGenerator, spWScaleAndSizeExtractor, spWCvMatToOpInput},
                                           queueIn++, queueOut++);
                    else
                        mThreadManager.add(mThreadId, {spWIdGenerator, spWScaleAndSizeExtractor, spWCvMatToOpInput,
                                           spWCvMatToOpOutput}, queueIn++, queueOut++);
                }
1207
                else
1208
                    mThreadManager.add(mThreadId, spWIdGenerator, queueIn++, queueOut++);
G
gineshidalgo99 已提交
1209 1210 1211 1212 1213 1214 1215
            }
            // If custom user Worker in same thread or producer on same thread
            else
            {
                std::vector<TWorker> workersAux;
                // Custom user Worker
                if (!mUserInputWs.empty())
G
gineshidalgo99 已提交
1216
                    workersAux = mergeVectors(workersAux, mUserInputWs);
G
gineshidalgo99 已提交
1217
                // OpenPose producer
1218
                else if (wDatumProducer != nullptr)
G
gineshidalgo99 已提交
1219
                    workersAux = mergeVectors(workersAux, {wDatumProducer});
G
gineshidalgo99 已提交
1220
                // Otherwise
1221 1222
                else if (mThreadManagerMode != ThreadManagerMode::Asynchronous
                            && mThreadManagerMode != ThreadManagerMode::AsynchronousIn)
G
gineshidalgo99 已提交
1223
                    error("No input selected.", __LINE__, __FUNCTION__, __FILE__);
1224 1225 1226 1227 1228
                // ID generator
                workersAux = mergeVectors(workersAux, {spWIdGenerator});
                // Scale & cv::Mat to OP format
                if (spWScaleAndSizeExtractor != nullptr && spWCvMatToOpInput != nullptr)
                    workersAux = mergeVectors(workersAux, {spWScaleAndSizeExtractor,
1229
                                                           spWCvMatToOpInput});
1230 1231 1232
                // cv::Mat to output format
                if (spWCvMatToOpOutput != nullptr)
                    workersAux = mergeVectors(workersAux, {spWCvMatToOpOutput});
1233 1234
                // Thread 0 or 1, queues 0 -> 1
                mThreadManager.add(mThreadId, workersAux, queueIn++, queueOut++);
G
gineshidalgo99 已提交
1235 1236 1237
            }
            threadIdPP();
            // Pose estimation & rendering
1238 1239
            // Thread 1 or 2...X, queues 1 -> 2, X = 2 + #GPUs
            if (!spWPoses.empty())
G
gineshidalgo99 已提交
1240
            {
G
gineshidalgo99 已提交
1241
                if (mMultiThreadEnabled)
G
gineshidalgo99 已提交
1242 1243 1244 1245 1246 1247 1248 1249
                {
                    for (auto& wPose : spWPoses)
                    {
                        mThreadManager.add(mThreadId, wPose, queueIn, queueOut);
                        threadIdPP();
                    }
                }
                else
G
gineshidalgo99 已提交
1250
                {
G
gineshidalgo99 已提交
1251 1252 1253
                    if (spWPoses.size() > 1)
                        log("Multi-threading disabled, only 1 thread running. All GPUs have been disabled but the"
                            " first one, which is defined by gpuNumberStart (e.g. in the OpenPose demo, it is set"
1254
                            " with the `--num_gpu_start` flag).", Priority::High);
G
gineshidalgo99 已提交
1255
                    mThreadManager.add(mThreadId, spWPoses.at(0), queueIn, queueOut);
G
gineshidalgo99 已提交
1256
                }
G
gineshidalgo99 已提交
1257 1258 1259 1260 1261 1262 1263 1264 1265
                queueIn++;
                queueOut++;
            }
            // If custom user Worker and uses its own thread
            if (!mUserPostProcessingWs.empty() && mUserPostProcessingWsOnNewThread)
            {
                // Post processing workers
                if (!mPostProcessingWs.empty())
                {
1266 1267
                    // Thread 2 or 3, queues 2 -> 3
                    mThreadManager.add(mThreadId, mPostProcessingWs, queueIn++, queueOut++);
G
gineshidalgo99 已提交
1268 1269 1270
                    threadIdPP();
                }
                // User processing workers
1271 1272
                // Thread 3 or 4, queues 3 -> 4
                mThreadManager.add(mThreadId, mUserPostProcessingWs, queueIn++, queueOut++);
G
gineshidalgo99 已提交
1273 1274 1275 1276
                threadIdPP();
                // Output workers
                if (!mOutputWs.empty())
                {
1277 1278
                    // Thread 4 or 5, queues 4 -> 5
                    mThreadManager.add(mThreadId, mOutputWs, queueIn++, queueOut++);
G
gineshidalgo99 已提交
1279 1280 1281 1282 1283 1284 1285
                    threadIdPP();
                }
            }
            // If custom user Worker in same thread or producer on same thread
            else
            {
                // Post processing workers + User post processing workers + Output workers
G
gineshidalgo99 已提交
1286 1287
                auto workersAux = mergeVectors(mPostProcessingWs, mUserPostProcessingWs);
                workersAux = mergeVectors(workersAux, mOutputWs);
G
gineshidalgo99 已提交
1288 1289
                if (!workersAux.empty())
                {
1290 1291
                    // Thread 2 or 3, queues 2 -> 3
                    mThreadManager.add(mThreadId, workersAux, queueIn++, queueOut++);
G
gineshidalgo99 已提交
1292 1293 1294 1295
                    threadIdPP();
                }
            }
            // User output worker
1296 1297
            // Thread Y, queues Q -> Q+1
            if (!mUserOutputWs.empty())
G
gineshidalgo99 已提交
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
            {
                if (mUserOutputWsOnNewThread)
                {
                    mThreadManager.add(mThreadId, mUserOutputWs, queueIn++, queueOut++);
                    threadIdPP();
                }
                else
                    mThreadManager.add(mThreadId-1, mUserOutputWs, queueIn++, queueOut++);
            }
            // OpenPose GUI
            if (spWGui != nullptr)
            {
1310 1311
                // Thread Y+1, queues Q+1 -> Q+2
                mThreadManager.add(mThreadId, spWGui, queueIn++, queueOut++);
G
gineshidalgo99 已提交
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
                threadIdPP();
            }
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }

    template<typename TDatums, typename TWorker, typename TQueue>
1323
    unsigned long long Wrapper<TDatums, TWorker, TQueue>::threadIdPP()
G
gineshidalgo99 已提交
1324 1325 1326
    {
        try
        {
G
gineshidalgo99 已提交
1327
            if (mMultiThreadEnabled)
G
gineshidalgo99 已提交
1328 1329 1330 1331 1332 1333
                mThreadId++;
            return mThreadId;
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
1334
            return 0ull;
G
gineshidalgo99 已提交
1335 1336 1337 1338 1339 1340
        }
    }

    extern template class Wrapper<DATUM_BASE_NO_PTR>;
}

1341
#endif // OPENPOSE_WRAPPER_WRAPPER_HPP