wrapperAuxiliary.hpp 66.8 KB
Newer Older
G
Gines 已提交
1 2
#ifndef OPENPOSE_WRAPPER_WRAPPER_AUXILIARY_HPP
#define OPENPOSE_WRAPPER_WRAPPER_AUXILIARY_HPP
G
gineshidalgo99 已提交
3

G
gineshidalgo99 已提交
4 5
#include <openpose/thread/headers.hpp>
#include <openpose/wrapper/enumClasses.hpp>
6
#include <openpose/wrapper/wrapperStructExtra.hpp>
G
gineshidalgo99 已提交
7
#include <openpose/wrapper/wrapperStructFace.hpp>
8
#include <openpose/wrapper/wrapperStructGui.hpp>
G
gineshidalgo99 已提交
9 10 11 12 13 14 15 16
#include <openpose/wrapper/wrapperStructHand.hpp>
#include <openpose/wrapper/wrapperStructInput.hpp>
#include <openpose/wrapper/wrapperStructOutput.hpp>
#include <openpose/wrapper/wrapperStructPose.hpp>

namespace op
{
    /**
17
     * It checks that no wrong/contradictory flags are enabled for Wrapper(T)
G
gineshidalgo99 已提交
18 19 20
     * @param wrapperStructPose
     * @param wrapperStructFace
     * @param wrapperStructHand
21
     * @param wrapperStructExtra
G
gineshidalgo99 已提交
22 23 24 25
     * @param wrapperStructInput
     * @param wrapperStructOutput
     * @param renderOutput
     * @param userOutputWsEmpty
G
gineshidalgo99 已提交
26
     * @param producerSharedPtr
G
gineshidalgo99 已提交
27 28
     * @param threadManagerMode
     */
G
gineshidalgo99 已提交
29 30 31 32
    OP_API void wrapperConfigureSanityChecks(
        WrapperStructPose& wrapperStructPose, const WrapperStructFace& wrapperStructFace,
        const WrapperStructHand& wrapperStructHand, const WrapperStructExtra& wrapperStructExtra,
        const WrapperStructInput& wrapperStructInput, const WrapperStructOutput& wrapperStructOutput,
33 34 35
        const WrapperStructGui& wrapperStructGui, const bool renderOutput, const bool userInputAndPreprocessingWsEmpty,
        const bool userOutputWsEmpty, const std::shared_ptr<Producer>& producerSharedPtr,
        const ThreadManagerMode threadManagerMode);
G
gineshidalgo99 已提交
36 37 38 39 40

    /**
     * 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.
41
     * Note that mThreadId must be re-initialized to 0 before starting a new Wrapper(T) configuration.
G
gineshidalgo99 已提交
42 43 44 45 46 47 48 49 50 51 52
     * @param threadId unsigned long long element with the current thread id value. I will be edited to the next
     * `desired thread id number.
     */
    OP_API void threadIdPP(unsigned long long& threadId, const bool multiThreadEnabled);

    /**
     * Set ThreadManager from TWorkers (private internal function).
     * After any configure() has been called, the TWorkers are initialized. This function resets the ThreadManager
     * and adds them.
     * Common code for start() and exec().
     */
G
gineshidalgo99 已提交
53 54
    template<typename TDatum,
             typename TDatums = std::vector<std::shared_ptr<TDatum>>,
G
gineshidalgo99 已提交
55 56
             typename TDatumsSP = std::shared_ptr<TDatums>,
             typename TWorker = std::shared_ptr<Worker<TDatumsSP>>>
G
Gines Hidalgo 已提交
57
    void configureThreadManager(
G
gineshidalgo99 已提交
58 59 60 61
        ThreadManager<TDatumsSP>& threadManager, const bool multiThreadEnabled,
        const ThreadManagerMode threadManagerMode, const WrapperStructPose& wrapperStructPose,
        const WrapperStructFace& wrapperStructFace, const WrapperStructHand& wrapperStructHand,
        const WrapperStructExtra& wrapperStructExtra, const WrapperStructInput& wrapperStructInput,
62
        const WrapperStructOutput& wrapperStructOutput, const WrapperStructGui& wrapperStructGui,
G
gineshidalgo99 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
        const std::array<std::vector<TWorker>, int(WorkerType::Size)>& userWs,
        const std::array<bool, int(WorkerType::Size)>& userWsOnNewThread);
}





// Implementation
#include <openpose/3d/headers.hpp>
#include <openpose/core/headers.hpp>
#include <openpose/face/headers.hpp>
#include <openpose/filestream/headers.hpp>
#include <openpose/gpu/gpu.hpp>
#include <openpose/gui/headers.hpp>
#include <openpose/hand/headers.hpp>
#include <openpose/pose/headers.hpp>
#include <openpose/producer/headers.hpp>
#include <openpose/tracking/headers.hpp>
#include <openpose/utilities/fileSystem.hpp>
#include <openpose/utilities/standard.hpp>
namespace op
{
G
gineshidalgo99 已提交
86
    template<typename TDatum, typename TDatums, typename TDatumsSP, typename TWorker>
G
gineshidalgo99 已提交
87 88 89 90 91
    void configureThreadManager(
        ThreadManager<TDatumsSP>& threadManager, const bool multiThreadEnabledTemp,
        const ThreadManagerMode threadManagerMode, const WrapperStructPose& wrapperStructPoseTemp,
        const WrapperStructFace& wrapperStructFace, const WrapperStructHand& wrapperStructHand,
        const WrapperStructExtra& wrapperStructExtra, const WrapperStructInput& wrapperStructInput,
92
        const WrapperStructOutput& wrapperStructOutput, const WrapperStructGui& wrapperStructGui,
G
gineshidalgo99 已提交
93 94 95 96 97 98 99
        const std::array<std::vector<TWorker>, int(WorkerType::Size)>& userWs,
        const std::array<bool, int(WorkerType::Size)>& userWsOnNewThread)
    {
        try
        {
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);

G
gineshidalgo99 已提交
100 101 102
            // Create producer
            auto producerSharedPtr = createProducer(
                wrapperStructInput.producerType, wrapperStructInput.producerString,
103
                wrapperStructInput.cameraResolution, wrapperStructInput.cameraParameterPath,
104
                wrapperStructInput.undistortImage, wrapperStructInput.numberViews);
G
gineshidalgo99 已提交
105

G
gineshidalgo99 已提交
106 107 108 109 110 111
            // Editable arguments
            auto wrapperStructPose = wrapperStructPoseTemp;
            auto multiThreadEnabled = multiThreadEnabledTemp;

            // User custom workers
            const auto& userInputWs = userWs[int(WorkerType::Input)];
112
            const auto& userPreProcessingWs = userWs[int(WorkerType::PreProcessing)];
G
gineshidalgo99 已提交
113 114 115
            const auto& userPostProcessingWs = userWs[int(WorkerType::PostProcessing)];
            const auto& userOutputWs = userWs[int(WorkerType::Output)];
            const auto userInputWsOnNewThread = userWsOnNewThread[int(WorkerType::Input)];
116
            const auto userPreProcessingWsOnNewThread = userWsOnNewThread[int(WorkerType::PreProcessing)];
G
gineshidalgo99 已提交
117 118 119 120 121 122 123 124 125 126
            const auto userPostProcessingWsOnNewThread = userWsOnNewThread[int(WorkerType::PostProcessing)];
            const auto userOutputWsOnNewThread = userWsOnNewThread[int(WorkerType::Output)];

            // Video seek
            const auto spVideoSeek = std::make_shared<std::pair<std::atomic<bool>, std::atomic<int>>>();
            // It cannot be directly included in the constructor (compiler error for copying std::atomic)
            spVideoSeek->first = false;
            spVideoSeek->second = 0;

            // Required parameters
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
            const auto gpuMode = getGpuMode();
            const auto renderModePose = (
                wrapperStructPose.renderMode != RenderMode::Auto
                    ? wrapperStructPose.renderMode
                    : (gpuMode == GpuMode::Cuda ? RenderMode::Gpu : RenderMode::Cpu));
            const auto renderModeFace = (
                wrapperStructFace.renderMode != RenderMode::Auto
                    ? wrapperStructFace.renderMode
                    : (gpuMode == GpuMode::Cuda ? RenderMode::Gpu : RenderMode::Cpu));
            const auto renderModeHand = (
                wrapperStructHand.renderMode != RenderMode::Auto
                    ? wrapperStructHand.renderMode
                    : (gpuMode == GpuMode::Cuda ? RenderMode::Gpu : RenderMode::Cpu));
            const auto renderOutput = renderModePose != RenderMode::None
                                        || renderModeFace != RenderMode::None
                                        || renderModeHand != RenderMode::None;
            const auto renderOutputGpu = renderModePose == RenderMode::Gpu
                || renderModeFace == RenderMode::Gpu
                || renderModeHand == RenderMode::Gpu;
            const auto renderFace = wrapperStructFace.enable && renderModeFace != RenderMode::None;
            const auto renderHand = wrapperStructHand.enable && renderModeHand != RenderMode::None;
            const auto renderHandGpu = wrapperStructHand.enable && renderModeHand == RenderMode::Gpu;
G
gineshidalgo99 已提交
149 150

            // Check no wrong/contradictory flags enabled
151
            const auto userInputAndPreprocessingWsEmpty = userInputWs.empty();
G
gineshidalgo99 已提交
152
            const auto userOutputWsEmpty = userOutputWs.empty();
G
gineshidalgo99 已提交
153 154
            wrapperConfigureSanityChecks(
                wrapperStructPose, wrapperStructFace, wrapperStructHand, wrapperStructExtra, wrapperStructInput,
155 156
                wrapperStructOutput, wrapperStructGui, renderOutput, userInputAndPreprocessingWsEmpty,
                userOutputWsEmpty, producerSharedPtr, threadManagerMode);
G
gineshidalgo99 已提交
157 158

            // Get number threads
G
Gines Hidalgo 已提交
159
            auto numberGpuThreads = wrapperStructPose.gpuNumber;
G
gineshidalgo99 已提交
160 161
            auto gpuNumberStart = wrapperStructPose.gpuNumberStart;
            // CPU --> 1 thread or no pose extraction
162
            if (gpuMode == GpuMode::NoGpu)
G
gineshidalgo99 已提交
163
            {
G
Gines Hidalgo 已提交
164
                numberGpuThreads = (wrapperStructPose.gpuNumber == 0 ? 0 : 1);
G
gineshidalgo99 已提交
165 166 167 168 169 170 171 172 173 174 175 176
                gpuNumberStart = 0;
                // Disabling multi-thread makes the code 400 ms faster (2.3 sec vs. 2.7 in i7-6850K)
                // and fixes the bug that the screen was not properly displayed and only refreshed sometimes
                // Note: The screen bug could be also fixed by using waitKey(30) rather than waitKey(1)
                multiThreadEnabled = false;
            }
            // GPU --> user picks (<= #GPUs)
            else
            {
                // Get total number GPUs
                const auto totalGpuNumber = getGpuNumber();
                // If number GPU < 0 --> set it to all the available GPUs
G
Gines Hidalgo 已提交
177
                if (numberGpuThreads < 0)
G
gineshidalgo99 已提交
178 179 180 181
                {
                    if (totalGpuNumber <= gpuNumberStart)
                        error("Number of initial GPU (`--number_gpu_start`) must be lower than the total number of"
                              " used GPUs (`--number_gpu`)", __LINE__, __FUNCTION__, __FILE__);
G
Gines Hidalgo 已提交
182
                    numberGpuThreads = totalGpuNumber - gpuNumberStart;
G
gineshidalgo99 已提交
183 184 185
                    // Reset initial GPU to 0 (we want them all)
                    // Logging message
                    log("Auto-detecting all available GPUs... Detected " + std::to_string(totalGpuNumber)
G
Gines Hidalgo 已提交
186
                        + " GPU(s), using " + std::to_string(numberGpuThreads) + " of them starting at GPU "
G
gineshidalgo99 已提交
187 188
                        + std::to_string(gpuNumberStart) + ".", Priority::High);
                }
189
                // Sanity check
G
Gines Hidalgo 已提交
190
                if (gpuNumberStart + numberGpuThreads > totalGpuNumber)
G
gineshidalgo99 已提交
191 192 193
                    error("Initial GPU selected (`--number_gpu_start`) + number GPUs to use (`--number_gpu`) must"
                          " be lower or equal than the total number of GPUs in your machine ("
                          + std::to_string(gpuNumberStart) + " + "
G
Gines Hidalgo 已提交
194
                          + std::to_string(numberGpuThreads) + " vs. "
G
gineshidalgo99 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208
                          + std::to_string(totalGpuNumber) + ").",
                          __LINE__, __FUNCTION__, __FILE__);
            }

            // Proper format
            const auto writeImagesCleaned = formatAsDirectory(wrapperStructOutput.writeImages);
            const auto writeKeypointCleaned = formatAsDirectory(wrapperStructOutput.writeKeypoint);
            const auto writeJsonCleaned = formatAsDirectory(wrapperStructOutput.writeJson);
            const auto writeHeatMapsCleaned = formatAsDirectory(wrapperStructOutput.writeHeatMaps);
            const auto modelFolder = formatAsDirectory(wrapperStructPose.modelFolder);

            // Common parameters
            auto finalOutputSize = wrapperStructPose.outputSize;
            Point<int> producerSize{-1,-1};
G
gineshidalgo99 已提交
209
            const auto oPProducer = (producerSharedPtr != nullptr);
G
gineshidalgo99 已提交
210 211 212 213 214
            if (oPProducer)
            {
                // 1. Set producer properties
                const auto displayProducerFpsMode = (wrapperStructInput.realTimeProcessing
                                                      ? ProducerFpsMode::OriginalFps : ProducerFpsMode::RetrievalFps);
G
gineshidalgo99 已提交
215 216 217 218
                producerSharedPtr->setProducerFpsMode(displayProducerFpsMode);
                producerSharedPtr->set(ProducerProperty::Flip, wrapperStructInput.frameFlip);
                producerSharedPtr->set(ProducerProperty::Rotation, wrapperStructInput.frameRotate);
                producerSharedPtr->set(ProducerProperty::AutoRepeat, wrapperStructInput.framesRepeat);
G
gineshidalgo99 已提交
219
                // 2. Set finalOutputSize
G
gineshidalgo99 已提交
220 221
                producerSize = Point<int>{(int)producerSharedPtr->get(CV_CAP_PROP_FRAME_WIDTH),
                                          (int)producerSharedPtr->get(CV_CAP_PROP_FRAME_HEIGHT)};
G
gineshidalgo99 已提交
222 223 224 225 226 227
                // Set finalOutputSize to input size if desired
                if (finalOutputSize.x == -1 || finalOutputSize.y == -1)
                    finalOutputSize = producerSize;
            }

            // Producer
228
            TWorker datumProducerW;
G
gineshidalgo99 已提交
229 230
            if (oPProducer)
            {
G
gineshidalgo99 已提交
231
                const auto datumProducer = std::make_shared<DatumProducer<TDatum>>(
G
gineshidalgo99 已提交
232
                    producerSharedPtr, wrapperStructInput.frameFirst, wrapperStructInput.frameStep,
G
gineshidalgo99 已提交
233
                    wrapperStructInput.frameLast, spVideoSeek
G
gineshidalgo99 已提交
234
                );
G
gineshidalgo99 已提交
235
                datumProducerW = std::make_shared<WDatumProducer<TDatum>>(datumProducer);
G
gineshidalgo99 已提交
236 237 238 239 240 241 242 243
            }
            else
                datumProducerW = nullptr;

            std::vector<std::shared_ptr<PoseExtractorNet>> poseExtractorNets;
            std::vector<std::shared_ptr<FaceExtractorNet>> faceExtractorNets;
            std::vector<std::shared_ptr<HandExtractorNet>> handExtractorNets;
            std::vector<std::shared_ptr<PoseGpuRenderer>> poseGpuRenderers;
G
Gines Hidalgo 已提交
244
            // CUDA vs. CPU resize
G
Gines Hidalgo 已提交
245
            std::vector<std::shared_ptr<CvMatToOpOutput>> cvMatToOpOutputs;
G
Gines Hidalgo 已提交
246
            std::vector<std::shared_ptr<OpOutputToCvMat>> opOutputToCvMats;
G
gineshidalgo99 已提交
247
            std::shared_ptr<PoseCpuRenderer> poseCpuRenderer;
248 249 250 251
            // Workers
            TWorker scaleAndSizeExtractorW;
            TWorker cvMatToOpInputW;
            TWorker cvMatToOpOutputW;
G
Gines Hidalgo 已提交
252 253
            bool addCvMatToOpOutput = renderOutput;
            bool addCvMatToOpOutputInCpu = addCvMatToOpOutput;
254 255 256 257
            std::vector<std::vector<TWorker>> poseExtractorsWs;
            std::vector<std::vector<TWorker>> poseTriangulationsWs;
            std::vector<std::vector<TWorker>> jointAngleEstimationsWs;
            std::vector<TWorker> postProcessingWs;
G
Gines Hidalgo 已提交
258
            if (numberGpuThreads > 0)
G
gineshidalgo99 已提交
259 260 261 262 263 264 265 266 267
            {
                // Get input scales and sizes
                const auto scaleAndSizeExtractor = std::make_shared<ScaleAndSizeExtractor>(
                    wrapperStructPose.netInputSize, finalOutputSize, wrapperStructPose.scalesNumber,
                    wrapperStructPose.scaleGap
                );
                scaleAndSizeExtractorW = std::make_shared<WScaleAndSizeExtractor<TDatumsSP>>(scaleAndSizeExtractor);

                // Input cvMat to OpenPose input & output format
G
Gines Hidalgo 已提交
268
                // Note: resize on GPU reduces accuracy about 0.1%
G
Gines Hidalgo 已提交
269
                bool resizeOnCpu = true;
270
                // const auto resizeOnCpu = (wrapperStructPose.poseMode != PoseMode::Enabled);
G
Gines Hidalgo 已提交
271 272 273 274 275 276 277 278
                if (resizeOnCpu)
                {
                    const auto gpuResize = false;
                    const auto cvMatToOpInput = std::make_shared<CvMatToOpInput>(
                        wrapperStructPose.poseModel, gpuResize);
                    cvMatToOpInputW = std::make_shared<WCvMatToOpInput<TDatumsSP>>(cvMatToOpInput);
                }
                // Note: We realized that somehow doing it on GPU for any number of GPUs does speedup the whole OP
279
                resizeOnCpu = false;
280 281
                addCvMatToOpOutputInCpu = addCvMatToOpOutput
                    && (resizeOnCpu || !renderOutputGpu || wrapperStructPose.poseMode != PoseMode::Enabled);
G
Gines Hidalgo 已提交
282
                if (addCvMatToOpOutputInCpu)
G
gineshidalgo99 已提交
283
                {
G
Gines Hidalgo 已提交
284 285
                    const auto gpuResize = false;
                    const auto cvMatToOpOutput = std::make_shared<CvMatToOpOutput>(gpuResize);
G
gineshidalgo99 已提交
286 287 288 289 290 291
                    cvMatToOpOutputW = std::make_shared<WCvMatToOpOutput<TDatumsSP>>(cvMatToOpOutput);
                }

                // Pose estimators & renderers
                std::vector<TWorker> cpuRenderers;
                poseExtractorsWs.clear();
G
Gines Hidalgo 已提交
292
                poseExtractorsWs.resize(numberGpuThreads);
293
                if (wrapperStructPose.poseMode != PoseMode::Disabled)
G
gineshidalgo99 已提交
294 295
                {
                    // Pose estimators
G
Gines Hidalgo 已提交
296
                    for (auto gpuId = 0; gpuId < numberGpuThreads; gpuId++)
G
gineshidalgo99 已提交
297 298
                        poseExtractorNets.emplace_back(std::make_shared<PoseExtractorCaffe>(
                            wrapperStructPose.poseModel, modelFolder, gpuId + gpuNumberStart,
299
                            wrapperStructPose.heatMapTypes, wrapperStructPose.heatMapScaleMode,
G
gineshidalgo99 已提交
300
                            wrapperStructPose.addPartCandidates, wrapperStructPose.maximizePositives,
301
                            wrapperStructPose.protoTxtPath, wrapperStructPose.caffeModelPath,
302
                            wrapperStructPose.upsamplingRatio, wrapperStructPose.poseMode == PoseMode::Enabled,
G
gineshidalgo99 已提交
303
                            wrapperStructPose.enableGoogleLogging
G
gineshidalgo99 已提交
304 305 306
                        ));

                    // Pose renderers
307
                    if (renderOutputGpu || renderModePose == RenderMode::Cpu)
G
gineshidalgo99 已提交
308
                    {
309
                        // If renderModePose != RenderMode::Gpu but renderOutput, then we create an
G
gineshidalgo99 已提交
310
                        // alpha = 0 pose renderer in order to keep the removing background option
311
                        const auto alphaKeypoint = (renderModePose != RenderMode::None
G
gineshidalgo99 已提交
312
                                                    ? wrapperStructPose.alphaKeypoint : 0.f);
313
                        const auto alphaHeatMap = (renderModePose != RenderMode::None
G
gineshidalgo99 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327
                                                    ? wrapperStructPose.alphaHeatMap : 0.f);
                        // GPU rendering
                        if (renderOutputGpu)
                        {
                            for (const auto& poseExtractorNet : poseExtractorNets)
                            {
                                poseGpuRenderers.emplace_back(std::make_shared<PoseGpuRenderer>(
                                    wrapperStructPose.poseModel, poseExtractorNet, wrapperStructPose.renderThreshold,
                                    wrapperStructPose.blendOriginalFrame, alphaKeypoint,
                                    alphaHeatMap, wrapperStructPose.defaultPartToRender
                                ));
                            }
                        }
                        // CPU rendering
328
                        if (renderModePose == RenderMode::Cpu)
G
gineshidalgo99 已提交
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
                        {
                            poseCpuRenderer = std::make_shared<PoseCpuRenderer>(
                                wrapperStructPose.poseModel, wrapperStructPose.renderThreshold,
                                wrapperStructPose.blendOriginalFrame, alphaKeypoint, alphaHeatMap,
                                wrapperStructPose.defaultPartToRender);
                            cpuRenderers.emplace_back(std::make_shared<WPoseRenderer<TDatumsSP>>(poseCpuRenderer));
                        }
                    }
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);

                    // Pose extractor(s)
                    poseExtractorsWs.resize(poseExtractorNets.size());
                    const auto personIdExtractor = (wrapperStructExtra.identification
                        ? std::make_shared<PersonIdExtractor>() : nullptr);
                    // Keep top N people
                    // Added right after PoseExtractorNet to avoid:
                    // 1) Rendering people that are later deleted (wrong visualization).
                    // 2) Processing faces and hands on people that will be deleted (speed up).
                    // 3) Running tracking before deleting the people.
                    // Add KeepTopNPeople for each PoseExtractorNet
                    const auto keepTopNPeople = (wrapperStructPose.numberPeopleMax > 0 ?
                        std::make_shared<KeepTopNPeople>(wrapperStructPose.numberPeopleMax)
                        : nullptr);
                    // Person tracker
                    auto personTrackers = std::make_shared<std::vector<std::shared_ptr<PersonTracker>>>();
                    if (wrapperStructExtra.tracking > -1)
                        personTrackers->emplace_back(
                            std::make_shared<PersonTracker>(wrapperStructExtra.tracking == 0));
                    for (auto i = 0u; i < poseExtractorsWs.size(); i++)
                    {
                        // OpenPose keypoint detector + keepTopNPeople
                        //    + ID extractor (experimental) + tracking (experimental)
                        const auto poseExtractor = std::make_shared<PoseExtractor>(
                            poseExtractorNets.at(i), keepTopNPeople, personIdExtractor, personTrackers,
                            wrapperStructPose.numberPeopleMax, wrapperStructExtra.tracking);
G
Gines Hidalgo 已提交
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
                        // If we want the initial image resize on GPU
                        if (cvMatToOpInputW == nullptr)
                        {
                            const auto gpuResize = true;
                            const auto cvMatToOpInput = std::make_shared<CvMatToOpInput>(
                                wrapperStructPose.poseModel, gpuResize);
                            poseExtractorsWs.at(i).emplace_back(
                                std::make_shared<WCvMatToOpInput<TDatumsSP>>(cvMatToOpInput));
                        }
                        // If we want the final image resize on GPU
                        if (addCvMatToOpOutput && cvMatToOpOutputW == nullptr)
                        {
                            const auto gpuResize = true;
                            cvMatToOpOutputs.emplace_back(std::make_shared<CvMatToOpOutput>(gpuResize));
                            poseExtractorsWs.at(i).emplace_back(
                                std::make_shared<WCvMatToOpOutput<TDatumsSP>>(cvMatToOpOutputs.back()));
                        }
                        poseExtractorsWs.at(i).emplace_back(
                            std::make_shared<WPoseExtractor<TDatumsSP>>(poseExtractor));
                        // poseExtractorsWs.at(i) = {std::make_shared<WPoseExtractor<TDatumsSP>>(poseExtractor)};
G
gineshidalgo99 已提交
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
                        // // Just OpenPose keypoint detector
                        // poseExtractorsWs.at(i) = {std::make_shared<WPoseExtractorNet<TDatumsSP>>(
                        //     poseExtractorNets.at(i))};
                    }

                    // // (Before tracking / id extractor)
                    // // Added right after PoseExtractorNet to avoid:
                    // // 1) Rendering people that are later deleted (wrong visualization).
                    // // 2) Processing faces and hands on people that will be deleted (speed up).
                    // if (wrapperStructPose.numberPeopleMax > 0)
                    // {
                    //     // Add KeepTopNPeople for each PoseExtractorNet
                    //     const auto keepTopNPeople = std::make_shared<KeepTopNPeople>(
                    //         wrapperStructPose.numberPeopleMax);
                    //     for (auto& wPose : poseExtractorsWs)
                    //         wPose.emplace_back(std::make_shared<WKeepTopNPeople<TDatumsSP>>(keepTopNPeople));
                    // }
                }
G
gineshidalgo99 已提交
402
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
403

G
Gines Hidalgo 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
                // Pose renderer(s)
                if (!poseGpuRenderers.empty())
                {
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                    for (auto i = 0u; i < poseExtractorsWs.size(); i++)
                    {
                        poseExtractorsWs.at(i).emplace_back(std::make_shared<WPoseRenderer<TDatumsSP>>(
                            poseGpuRenderers.at(i)));
                        // Get shared params
                        if (!cvMatToOpOutputs.empty())
                            poseGpuRenderers.at(i)->setSharedParameters(
                                cvMatToOpOutputs.at(i)->getSharedParameters());
                    }
                }
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);

G
gineshidalgo99 已提交
420 421 422
                // Face extractor(s)
                if (wrapperStructFace.enable)
                {
G
gineshidalgo99 已提交
423
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
424
                    // Face detector
G
gineshidalgo99 已提交
425 426
                    // OpenPose body-based face detector
                    if (wrapperStructFace.detector == Detector::Body)
G
gineshidalgo99 已提交
427
                    {
G
gineshidalgo99 已提交
428
                        // Sanity check
429
                        if (wrapperStructPose.poseMode == PoseMode::Disabled)
G
gineshidalgo99 已提交
430 431 432 433
                            error("Body keypoint detection is disabled but face Detector is set to Body. Either"
                                  " re-enable OpenPose body or select a different face Detector (`--face_detector`).",
                                  __LINE__, __FUNCTION__, __FILE__);
                        // Constructors
G
gineshidalgo99 已提交
434 435 436 437 438
                        const auto faceDetector = std::make_shared<FaceDetector>(wrapperStructPose.poseModel);
                        for (auto& wPose : poseExtractorsWs)
                            wPose.emplace_back(std::make_shared<WFaceDetector<TDatumsSP>>(faceDetector));
                    }
                    // OpenCV face detector
G
gineshidalgo99 已提交
439
                    else if (wrapperStructFace.detector == Detector::OpenCV)
G
gineshidalgo99 已提交
440 441 442 443 444 445 446 447 448 449 450 451
                    {
                        log("Body keypoint detection is disabled. Hence, using OpenCV face detector (much less"
                            " accurate but faster).", Priority::High);
                        for (auto& wPose : poseExtractorsWs)
                        {
                            // 1 FaceDetectorOpenCV per thread, OpenCV face detector is not thread-safe
                            const auto faceDetectorOpenCV = std::make_shared<FaceDetectorOpenCV>(modelFolder);
                            wPose.emplace_back(
                                std::make_shared<WFaceDetectorOpenCV<TDatumsSP>>(faceDetectorOpenCV)
                            );
                        }
                    }
G
gineshidalgo99 已提交
452 453 454 455 456
                    // If provided by user: We do not need to create a FaceDetector
                    // Unknown face Detector
                    else if (wrapperStructFace.detector != Detector::Provided)
                        error("Unknown face Detector. Select a valid face Detector (`--face_detector`).",
                              __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
457 458 459 460 461 462 463
                    // Face keypoint extractor
                    for (auto gpu = 0u; gpu < poseExtractorsWs.size(); gpu++)
                    {
                        // Face keypoint extractor
                        const auto netOutputSize = wrapperStructFace.netInputSize;
                        const auto faceExtractorNet = std::make_shared<FaceExtractorCaffe>(
                            wrapperStructFace.netInputSize, netOutputSize, modelFolder,
464
                            gpu + gpuNumberStart, wrapperStructPose.heatMapTypes, wrapperStructPose.heatMapScaleMode,
G
gineshidalgo99 已提交
465 466 467 468 469 470 471
                            wrapperStructPose.enableGoogleLogging
                        );
                        faceExtractorNets.emplace_back(faceExtractorNet);
                        poseExtractorsWs.at(gpu).emplace_back(
                            std::make_shared<WFaceExtractorNet<TDatumsSP>>(faceExtractorNet));
                    }
                }
G
gineshidalgo99 已提交
472
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
473 474 475 476

                // Hand extractor(s)
                if (wrapperStructHand.enable)
                {
G
gineshidalgo99 已提交
477
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
478 479 480
                    const auto handDetector = std::make_shared<HandDetector>(wrapperStructPose.poseModel);
                    for (auto gpu = 0u; gpu < poseExtractorsWs.size(); gpu++)
                    {
G
gineshidalgo99 已提交
481 482 483
                        // Sanity check
                        if ((wrapperStructHand.detector == Detector::BodyWithTracking
                             || wrapperStructHand.detector == Detector::Body)
484
                            && wrapperStructPose.poseMode == PoseMode::Disabled)
G
gineshidalgo99 已提交
485 486 487
                            error("Body keypoint detection is disabled but hand Detector is set to Body. Either"
                                  " re-enable OpenPose body or select a different hand Detector (`--hand_detector`).",
                                  __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
488
                        // Hand detector
G
gineshidalgo99 已提交
489 490 491
                        // OpenPose body-based hand detector with tracking
                        if (wrapperStructHand.detector == Detector::BodyWithTracking)
                        {
G
gineshidalgo99 已提交
492
                            poseExtractorsWs.at(gpu).emplace_back(
G
Gines Hidalgo 已提交
493
                                std::make_shared<WHandDetectorTracking<TDatumsSP>>(handDetector));
G
gineshidalgo99 已提交
494 495 496 497
                        }
                        // OpenPose body-based hand detector
                        else if (wrapperStructHand.detector == Detector::Body)
                        {
G
gineshidalgo99 已提交
498 499
                            poseExtractorsWs.at(gpu).emplace_back(
                                std::make_shared<WHandDetector<TDatumsSP>>(handDetector));
G
gineshidalgo99 已提交
500 501 502 503 504 505
                        }
                        // If provided by user: We do not need to create a FaceDetector
                        // Unknown hand Detector
                        else if (wrapperStructHand.detector != Detector::Provided)
                            error("Unknown hand Detector. Select a valid hand Detector (`--hand_detector`).",
                                  __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
506 507 508 509 510
                        // Hand keypoint extractor
                        const auto netOutputSize = wrapperStructHand.netInputSize;
                        const auto handExtractorNet = std::make_shared<HandExtractorCaffe>(
                            wrapperStructHand.netInputSize, netOutputSize, modelFolder,
                            gpu + gpuNumberStart, wrapperStructHand.scalesNumber, wrapperStructHand.scaleRange,
511
                            wrapperStructPose.heatMapTypes, wrapperStructPose.heatMapScaleMode,
G
gineshidalgo99 已提交
512 513 514 515 516 517
                            wrapperStructPose.enableGoogleLogging
                        );
                        handExtractorNets.emplace_back(handExtractorNet);
                        poseExtractorsWs.at(gpu).emplace_back(
                            std::make_shared<WHandExtractorNet<TDatumsSP>>(handExtractorNet)
                            );
G
gineshidalgo99 已提交
518 519
                        // If OpenPose body-based hand detector with tracking
                        if (wrapperStructHand.detector == Detector::BodyWithTracking)
G
gineshidalgo99 已提交
520
                            poseExtractorsWs.at(gpu).emplace_back(
G
Gines Hidalgo 已提交
521
                                std::make_shared<WHandDetectorUpdate<TDatumsSP>>(handDetector));
G
gineshidalgo99 已提交
522 523
                    }
                }
G
gineshidalgo99 已提交
524
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
525 526 527 528

                // Face renderer(s)
                if (renderFace)
                {
G
gineshidalgo99 已提交
529
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
530
                    // CPU rendering
531
                    if (renderModeFace == RenderMode::Cpu)
G
gineshidalgo99 已提交
532 533
                    {
                        // Construct face renderer
G
Gines Hidalgo 已提交
534 535 536
                        const auto faceRenderer = std::make_shared<FaceCpuRenderer>(
                            wrapperStructFace.renderThreshold, wrapperStructFace.alphaKeypoint,
                            wrapperStructFace.alphaHeatMap);
G
gineshidalgo99 已提交
537 538 539 540
                        // Add worker
                        cpuRenderers.emplace_back(std::make_shared<WFaceRenderer<TDatumsSP>>(faceRenderer));
                    }
                    // GPU rendering
541
                    else if (renderModeFace == RenderMode::Gpu)
G
gineshidalgo99 已提交
542 543 544 545 546 547 548 549 550 551 552
                    {
                        for (auto i = 0u; i < poseExtractorsWs.size(); i++)
                        {
                            // 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())
                            {
G
Gines Hidalgo 已提交
553 554
                                // const bool isLastRenderer = !renderHandGpu;
                                const bool isLastRenderer = !renderHandGpu && !(addCvMatToOpOutput && !addCvMatToOpOutputInCpu);
G
gineshidalgo99 已提交
555
                                const auto renderer = std::static_pointer_cast<PoseGpuRenderer>(
G
Gines Hidalgo 已提交
556 557 558
                                    poseGpuRenderers.at(i));
                                faceRenderer->setSharedParametersAndIfLast(
                                    renderer->getSharedParameters(), isLastRenderer);
G
gineshidalgo99 已提交
559 560 561 562 563 564 565 566 567
                            }
                            // Add worker
                            poseExtractorsWs.at(i).emplace_back(
                                std::make_shared<WFaceRenderer<TDatumsSP>>(faceRenderer));
                        }
                    }
                    else
                        error("Unknown RenderMode.", __LINE__, __FUNCTION__, __FILE__);
                }
G
gineshidalgo99 已提交
568
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
569 570 571 572

                // Hand renderer(s)
                if (renderHand)
                {
G
gineshidalgo99 已提交
573
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
574
                    // CPU rendering
575
                    if (renderModeHand == RenderMode::Cpu)
G
gineshidalgo99 已提交
576 577
                    {
                        // Construct hand renderer
G
Gines Hidalgo 已提交
578 579 580
                        const auto handRenderer = std::make_shared<HandCpuRenderer>(
                            wrapperStructHand.renderThreshold, wrapperStructHand.alphaKeypoint,
                            wrapperStructHand.alphaHeatMap);
G
gineshidalgo99 已提交
581 582 583 584
                        // Add worker
                        cpuRenderers.emplace_back(std::make_shared<WHandRenderer<TDatumsSP>>(handRenderer));
                    }
                    // GPU rendering
585
                    else if (renderModeHand == RenderMode::Gpu)
G
gineshidalgo99 已提交
586 587 588 589 590 591 592 593 594 595 596
                    {
                        for (auto i = 0u; i < poseExtractorsWs.size(); i++)
                        {
                            // 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())
                            {
G
Gines Hidalgo 已提交
597 598
                                // const bool isLastRenderer = true;
                                const bool isLastRenderer = !(addCvMatToOpOutput && !addCvMatToOpOutputInCpu);
G
gineshidalgo99 已提交
599
                                const auto renderer = std::static_pointer_cast<PoseGpuRenderer>(
G
Gines Hidalgo 已提交
600 601 602
                                    poseGpuRenderers.at(i));
                                handRenderer->setSharedParametersAndIfLast(
                                    renderer->getSharedParameters(), isLastRenderer);
G
gineshidalgo99 已提交
603 604 605 606 607 608 609 610 611
                            }
                            // Add worker
                            poseExtractorsWs.at(i).emplace_back(
                                std::make_shared<WHandRenderer<TDatumsSP>>(handRenderer));
                        }
                    }
                    else
                        error("Unknown RenderMode.", __LINE__, __FUNCTION__, __FILE__);
                }
G
gineshidalgo99 已提交
612
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
613

G
Gines Hidalgo 已提交
614 615 616 617 618 619 620 621
                // Frames processor (OpenPose format -> cv::Mat format)
                if (addCvMatToOpOutput && !addCvMatToOpOutputInCpu)
                {
                    // for (auto& poseExtractorsW : poseExtractorsWs)
                    for (auto i = 0u ; i < poseExtractorsWs.size() ; ++i)
                    {
                        const auto gpuResize = true;
                        opOutputToCvMats.emplace_back(std::make_shared<OpOutputToCvMat>(gpuResize));
622
                        poseExtractorsWs.at(i).emplace_back(
G
Gines Hidalgo 已提交
623 624 625 626 627 628 629 630
                            std::make_shared<WOpOutputToCvMat<TDatumsSP>>(opOutputToCvMats.back()));
                        // Assign shared parameters
                        opOutputToCvMats.back()->setSharedParameters(
                            cvMatToOpOutputs.at(i)->getSharedParameters());
                    }
                }
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);

G
gineshidalgo99 已提交
631 632 633 634
                // 3-D reconstruction
                poseTriangulationsWs.clear();
                if (wrapperStructExtra.reconstruct3d)
                {
G
gineshidalgo99 已提交
635
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
636 637 638 639 640 641 642 643 644 645
                    // For all (body/face/hands): PoseTriangulations ~30 msec, 8 GPUS ~30 msec for keypoint estimation
                    poseTriangulationsWs.resize(fastMax(1, int(poseExtractorsWs.size() / 4)));
                    for (auto i = 0u ; i < poseTriangulationsWs.size() ; i++)
                    {
                        const auto poseTriangulation = std::make_shared<PoseTriangulation>(
                            wrapperStructExtra.minViews3d);
                        poseTriangulationsWs.at(i) = {std::make_shared<WPoseTriangulation<TDatumsSP>>(
                            poseTriangulation)};
                    }
                }
G
gineshidalgo99 已提交
646
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
647
                // Itermediate workers (e.g., OpenPose format to cv::Mat, json & frames recorder, ...)
G
gineshidalgo99 已提交
648 649 650 651 652 653 654 655 656 657
                postProcessingWs.clear();
                // // Person ID identification (when no multi-thread and no dependency on tracking)
                // if (wrapperStructExtra.identification)
                // {
                //     const auto personIdExtractor = std::make_shared<PersonIdExtractor>();
                //     postProcessingWs.emplace_back(
                //         std::make_shared<WPersonIdExtractor<TDatumsSP>>(personIdExtractor)
                //     );
                // }
                // Frames processor (OpenPose format -> cv::Mat format)
G
Gines Hidalgo 已提交
658
                if (addCvMatToOpOutputInCpu)
G
gineshidalgo99 已提交
659
                {
G
gineshidalgo99 已提交
660
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
661 662 663 664
                    postProcessingWs = mergeVectors(postProcessingWs, cpuRenderers);
                    const auto opOutputToCvMat = std::make_shared<OpOutputToCvMat>();
                    postProcessingWs.emplace_back(std::make_shared<WOpOutputToCvMat<TDatumsSP>>(opOutputToCvMat));
                }
G
gineshidalgo99 已提交
665
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
666 667
                // Re-scale pose if desired
                // If desired scale is not the current input
668
                if (wrapperStructPose.keypointScaleMode != ScaleMode::InputResolution
G
gineshidalgo99 已提交
669
                    // and desired scale is not output when size(input) = size(output)
670
                    && !(wrapperStructPose.keypointScaleMode == ScaleMode::OutputResolution &&
G
gineshidalgo99 已提交
671 672
                         (finalOutputSize == producerSize || finalOutputSize.x <= 0 || finalOutputSize.y <= 0))
                    // and desired scale is not net output when size(input) = size(net output)
673
                    && !(wrapperStructPose.keypointScaleMode == ScaleMode::NetOutputResolution
G
gineshidalgo99 已提交
674 675 676
                         && producerSize == wrapperStructPose.netInputSize))
                {
                    // Then we must rescale the keypoints
677
                    auto keypointScaler = std::make_shared<KeypointScaler>(wrapperStructPose.keypointScaleMode);
G
gineshidalgo99 已提交
678 679 680
                    postProcessingWs.emplace_back(std::make_shared<WKeypointScaler<TDatumsSP>>(keypointScaler));
                }
            }
G
gineshidalgo99 已提交
681
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
682 683

            // IK/Adam
684 685
            const auto displayAdam = wrapperStructGui.displayMode == DisplayMode::DisplayAdam
                                     || (wrapperStructGui.displayMode == DisplayMode::DisplayAll
G
gineshidalgo99 已提交
686 687 688 689 690
                                         && wrapperStructExtra.ikThreads > 0);
            jointAngleEstimationsWs.clear();
#ifdef USE_3D_ADAM_MODEL
            if (wrapperStructExtra.ikThreads > 0)
            {
G
gineshidalgo99 已提交
691
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
692 693 694 695 696 697 698 699 700
                jointAngleEstimationsWs.resize(wrapperStructExtra.ikThreads);
                // Pose extractor(s)
                for (auto i = 0u; i < jointAngleEstimationsWs.size(); i++)
                {
                    const auto jointAngleEstimation = std::make_shared<JointAngleEstimation>(displayAdam);
                    jointAngleEstimationsWs.at(i) = {std::make_shared<WJointAngleEstimation<TDatumsSP>>(
                        jointAngleEstimation)};
                }
            }
G
gineshidalgo99 已提交
701
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
702 703 704
#endif

            // Output workers
705
            std::vector<TWorker> outputWs;
G
gineshidalgo99 已提交
706 707 708
            // Print verbose
            if (wrapperStructOutput.verbose > 0.)
            {
G
gineshidalgo99 已提交
709
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
710 711 712 713
                const auto verbosePrinter = std::make_shared<VerbosePrinter>(
                    wrapperStructOutput.verbose, producerSharedPtr->get(CV_CAP_PROP_FRAME_COUNT));
                outputWs.emplace_back(std::make_shared<WVerbosePrinter<TDatumsSP>>(verbosePrinter));
            }
G
gineshidalgo99 已提交
714
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
715
            // Send information (e.g., to Unity) though UDP client-server communication
G
gineshidalgo99 已提交
716

G
gineshidalgo99 已提交
717 718 719
#ifdef USE_3D_ADAM_MODEL
            if (!wrapperStructOutput.udpHost.empty() && !wrapperStructOutput.udpPort.empty())
            {
G
gineshidalgo99 已提交
720
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
721 722 723 724
                const auto udpSender = std::make_shared<UdpSender>(wrapperStructOutput.udpHost,
                                                                   wrapperStructOutput.udpPort);
                outputWs.emplace_back(std::make_shared<WUdpSender<TDatumsSP>>(udpSender));
            }
G
gineshidalgo99 已提交
725
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
726 727 728 729
#endif
            // Write people pose data on disk (json for OpenCV >= 3, xml, yml...)
            if (!writeKeypointCleaned.empty())
            {
G
gineshidalgo99 已提交
730
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
731 732 733 734 735 736 737 738
                const auto keypointSaver = std::make_shared<KeypointSaver>(writeKeypointCleaned,
                                                                           wrapperStructOutput.writeKeypointFormat);
                outputWs.emplace_back(std::make_shared<WPoseSaver<TDatumsSP>>(keypointSaver));
                if (wrapperStructFace.enable)
                    outputWs.emplace_back(std::make_shared<WFaceSaver<TDatumsSP>>(keypointSaver));
                if (wrapperStructHand.enable)
                    outputWs.emplace_back(std::make_shared<WHandSaver<TDatumsSP>>(keypointSaver));
            }
G
gineshidalgo99 已提交
739
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
740
            // Write OpenPose output data on disk in JSON format (body/hand/face keypoints, body part locations if
G
gineshidalgo99 已提交
741 742 743
            // enabled, etc.)
            if (!writeJsonCleaned.empty())
            {
G
gineshidalgo99 已提交
744
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
745 746 747
                const auto peopleJsonSaver = std::make_shared<PeopleJsonSaver>(writeJsonCleaned);
                outputWs.emplace_back(std::make_shared<WPeopleJsonSaver<TDatumsSP>>(peopleJsonSaver));
            }
G
gineshidalgo99 已提交
748
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
749
            // Write people pose/foot/face/hand/etc. data on disk (COCO validation JSON format)
G
gineshidalgo99 已提交
750 751
            if (!wrapperStructOutput.writeCocoJson.empty())
            {
G
gineshidalgo99 已提交
752
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
753 754
                // If humanFormat: bigger size (& maybe slower to process), but easier for user to read it
                const auto humanFormat = true;
G
gineshidalgo99 已提交
755
                const auto cocoJsonSaver = std::make_shared<CocoJsonSaver>(
756
                    wrapperStructOutput.writeCocoJson, wrapperStructPose.poseModel, humanFormat,
757
                    wrapperStructOutput.writeCocoJsonVariants,
G
gineshidalgo99 已提交
758 759
                    (wrapperStructPose.poseModel != PoseModel::CAR_22
                        && wrapperStructPose.poseModel != PoseModel::CAR_12
G
gineshidalgo99 已提交
760 761
                        ? CocoJsonFormat::Body : CocoJsonFormat::Car),
                    wrapperStructOutput.writeCocoJsonVariant);
G
gineshidalgo99 已提交
762 763
                outputWs.emplace_back(std::make_shared<WCocoJsonSaver<TDatumsSP>>(cocoJsonSaver));
            }
G
gineshidalgo99 已提交
764 765
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
766 767 768
            // Write frames as desired image format on hard disk
            if (!writeImagesCleaned.empty())
            {
G
gineshidalgo99 已提交
769
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
770 771 772 773
                const auto imageSaver = std::make_shared<ImageSaver>(writeImagesCleaned,
                                                                     wrapperStructOutput.writeImagesFormat);
                outputWs.emplace_back(std::make_shared<WImageSaver<TDatumsSP>>(imageSaver));
            }
G
gineshidalgo99 已提交
774
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
775 776 777
            auto originalVideoFps = 0.;
            if (!wrapperStructOutput.writeVideo.empty() || !wrapperStructOutput.writeVideo3D.empty()
                || !wrapperStructOutput.writeBvh.empty())
G
gineshidalgo99 已提交
778
            {
G
gineshidalgo99 已提交
779
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
780
                if (wrapperStructOutput.writeVideoFps <= 0
G
gineshidalgo99 已提交
781
                    && (!oPProducer || producerSharedPtr->get(CV_CAP_PROP_FPS) <= 0))
782 783 784 785
                    error("The frame rate of the frames producer is unknown. Set `--write_video_fps` to your desired"
                          " FPS if you wanna record video (`--write_video`). E.g., if it is a folder of images, you"
                          " will have to know or guess the frame rate; if it is a webcam, you should use the OpenPose"
                          " displayed FPS as desired value. If you do not care, simply add `--write_video_fps 30`.",
G
gineshidalgo99 已提交
786
                          __LINE__, __FUNCTION__, __FILE__);
787
                originalVideoFps = (
788 789
                    wrapperStructOutput.writeVideoFps > 0 ?
                    wrapperStructOutput.writeVideoFps : producerSharedPtr->get(CV_CAP_PROP_FPS));
790
            }
G
gineshidalgo99 已提交
791
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
792 793 794
            // Write frames as *.avi video on hard disk
            if (!wrapperStructOutput.writeVideo.empty())
            {
G
gineshidalgo99 已提交
795
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
796
                // Sanity checks
797 798 799 800
                if (!oPProducer)
                    error("Video file can only be recorded inside `wrapper/wrapper.hpp` if the producer"
                          " is one of the default ones (e.g., video, webcam, ...).",
                          __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
801 802 803 804 805
                if (wrapperStructOutput.writeVideoWithAudio && producerSharedPtr->getType() != ProducerType::Video)
                    error("Audio can only be added to the output saved video if the input is also a video (either"
                          " disable `--write_video_with_audio` or use a video as input with `--video`).",
                          __LINE__, __FUNCTION__, __FILE__);
                // Create video saver worker
806
                const auto videoSaver = std::make_shared<VideoSaver>(
G
gineshidalgo99 已提交
807 808
                    wrapperStructOutput.writeVideo, CV_FOURCC('M','J','P','G'), originalVideoFps,
                    (wrapperStructOutput.writeVideoWithAudio ? wrapperStructInput.producerString : ""));
809 810
                outputWs.emplace_back(std::make_shared<WVideoSaver<TDatumsSP>>(videoSaver));
            }
G
gineshidalgo99 已提交
811
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
812
            // Write joint angles as *.bvh file on hard disk
G
gineshidalgo99 已提交
813
#ifdef USE_3D_ADAM_MODEL
814 815
            if (!wrapperStructOutput.writeBvh.empty())
            {
G
gineshidalgo99 已提交
816
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
817 818 819 820
                const auto bvhSaver = std::make_shared<BvhSaver>(
                    wrapperStructOutput.writeBvh, JointAngleEstimation::getTotalModel(), originalVideoFps
                );
                outputWs.emplace_back(std::make_shared<WBvhSaver<TDatumsSP>>(bvhSaver));
821
            }
G
gineshidalgo99 已提交
822
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
823
#endif
G
gineshidalgo99 已提交
824 825 826
            // Write heat maps as desired image format on hard disk
            if (!writeHeatMapsCleaned.empty())
            {
G
gineshidalgo99 已提交
827
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
828 829
                const auto heatMapSaver = std::make_shared<HeatMapSaver>(
                    writeHeatMapsCleaned, wrapperStructOutput.writeHeatMapsFormat);
G
gineshidalgo99 已提交
830 831
                outputWs.emplace_back(std::make_shared<WHeatMapSaver<TDatumsSP>>(heatMapSaver));
            }
G
gineshidalgo99 已提交
832
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
833
            // Add frame information for GUI
834
            const bool guiEnabled = (wrapperStructGui.displayMode != DisplayMode::NoDisplay);
G
gineshidalgo99 已提交
835 836
            // 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
837 838 839
            if (wrapperStructGui.guiVerbose && (guiEnabled || !userOutputWs.empty()
                                                || threadManagerMode == ThreadManagerMode::Asynchronous
                                                || threadManagerMode == ThreadManagerMode::AsynchronousOut))
G
gineshidalgo99 已提交
840
            {
G
gineshidalgo99 已提交
841
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
Gines Hidalgo 已提交
842
                const auto guiInfoAdder = std::make_shared<GuiInfoAdder>(numberGpuThreads, guiEnabled);
G
gineshidalgo99 已提交
843 844
                outputWs.emplace_back(std::make_shared<WGuiInfoAdder<TDatumsSP>>(guiInfoAdder));
            }
G
gineshidalgo99 已提交
845
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
846
            // Minimal graphical user interface (GUI)
847
            TWorker guiW;
848
            TWorker videoSaver3DW;
G
gineshidalgo99 已提交
849 850
            if (guiEnabled)
            {
G
gineshidalgo99 已提交
851
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
852 853
                // PoseRenderers to Renderers
                std::vector<std::shared_ptr<Renderer>> renderers;
854
                if (renderModePose == RenderMode::Cpu)
G
gineshidalgo99 已提交
855 856 857 858 859
                    renderers.emplace_back(std::static_pointer_cast<Renderer>(poseCpuRenderer));
                else
                    for (const auto& poseGpuRenderer : poseGpuRenderers)
                        renderers.emplace_back(std::static_pointer_cast<Renderer>(poseGpuRenderer));
                // Display
G
gineshidalgo99 已提交
860
                const auto numberViews = (producerSharedPtr != nullptr
G
gineshidalgo99 已提交
861
                    ? positiveIntRound(producerSharedPtr->get(ProducerProperty::NumberViews)) : 1);
862 863 864
                auto finalOutputSizeGui = finalOutputSize;
                if (numberViews > 1 && finalOutputSizeGui.x > 0)
                    finalOutputSizeGui.x *= numberViews;
G
gineshidalgo99 已提交
865 866 867 868
                // Adam (+3-D/2-D) display
                if (displayAdam)
                {
#ifdef USE_3D_ADAM_MODEL
G
gineshidalgo99 已提交
869
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
870 871
                    // Gui
                    const auto gui = std::make_shared<GuiAdam>(
872
                        finalOutputSizeGui, wrapperStructGui.fullScreen, threadManager.getIsRunningSharedPtr(),
G
gineshidalgo99 已提交
873
                        spVideoSeek, poseExtractorNets, faceExtractorNets, handExtractorNets, renderers,
874
                        wrapperStructGui.displayMode, JointAngleEstimation::getTotalModel(),
G
gineshidalgo99 已提交
875 876 877 878
                        wrapperStructOutput.writeVideoAdam
                    );
                    // WGui
                    guiW = {std::make_shared<WGuiAdam<TDatumsSP>>(gui)};
879 880 881 882
                    // Write 3D frames as *.avi video on hard disk
                    if (!wrapperStructOutput.writeVideo3D.empty())
                        error("3D video can only be recorded if 3D render is enabled.",
                              __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
883 884 885
#endif
                }
                // 3-D (+2-D) display
886 887
                else if (wrapperStructGui.displayMode == DisplayMode::Display3D
                    || wrapperStructGui.displayMode == DisplayMode::DisplayAll)
G
gineshidalgo99 已提交
888
                {
G
gineshidalgo99 已提交
889
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
890 891
                    // Gui
                    const auto gui = std::make_shared<Gui3D>(
892
                        finalOutputSizeGui, wrapperStructGui.fullScreen, threadManager.getIsRunningSharedPtr(),
G
gineshidalgo99 已提交
893
                        spVideoSeek, poseExtractorNets, faceExtractorNets, handExtractorNets, renderers,
894 895
                        wrapperStructPose.poseModel, wrapperStructGui.displayMode,
                        !wrapperStructOutput.writeVideo3D.empty()
G
gineshidalgo99 已提交
896 897 898
                    );
                    // WGui
                    guiW = {std::make_shared<WGui3D<TDatumsSP>>(gui)};
899 900 901 902
                    // Write 3D frames as *.avi video on hard disk
                    if (!wrapperStructOutput.writeVideo3D.empty())
                    {
                        const auto videoSaver = std::make_shared<VideoSaver>(
G
gineshidalgo99 已提交
903
                            wrapperStructOutput.writeVideo3D, CV_FOURCC('M','J','P','G'), originalVideoFps, "");
904 905
                        videoSaver3DW = std::make_shared<WVideoSaver3D<TDatumsSP>>(videoSaver);
                    }
G
gineshidalgo99 已提交
906 907
                }
                // 2-D display
908
                else if (wrapperStructGui.displayMode == DisplayMode::Display2D)
G
gineshidalgo99 已提交
909
                {
G
gineshidalgo99 已提交
910
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
911 912
                    // Gui
                    const auto gui = std::make_shared<Gui>(
913
                        finalOutputSizeGui, wrapperStructGui.fullScreen, threadManager.getIsRunningSharedPtr(),
G
gineshidalgo99 已提交
914 915 916 917
                        spVideoSeek, poseExtractorNets, faceExtractorNets, handExtractorNets, renderers
                    );
                    // WGui
                    guiW = {std::make_shared<WGui<TDatumsSP>>(gui)};
918 919 920 921
                    // Write 3D frames as *.avi video on hard disk
                    if (!wrapperStructOutput.writeVideo3D.empty())
                        error("3D video can only be recorded if 3D render is enabled.",
                              __LINE__, __FUNCTION__, __FILE__);
G
gineshidalgo99 已提交
922 923 924 925
                }
                else
                    error("Unknown DisplayMode.", __LINE__, __FUNCTION__, __FILE__);
            }
G
gineshidalgo99 已提交
926
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
927 928 929 930
            // Set FpsMax
            TWorker wFpsMax;
            if (wrapperStructPose.fpsMax > 0.)
                wFpsMax = std::make_shared<WFpsMax<TDatumsSP>>(wrapperStructPose.fpsMax);
G
gineshidalgo99 已提交
931 932 933 934 935 936 937 938 939
            // Set wrapper as configured
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);





            // The less number of queues -> the less threads opened, and potentially the less lag

940
            // Sanity checks
G
gineshidalgo99 已提交
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
            if ((datumProducerW == nullptr) == (userInputWs.empty())
                && threadManagerMode != ThreadManagerMode::Asynchronous
                && threadManagerMode != ThreadManagerMode::AsynchronousIn)
            {
                const auto message = "You need to have 1 and only 1 producer selected. You can introduce your own"
                                     " producer by using setWorker(WorkerType::Input, ...) or use the OpenPose"
                                     " default producer by configuring it in the configure function) or use the"
                                     " ThreadManagerMode::Asynchronous(In) mode.";
                error(message, __LINE__, __FUNCTION__, __FILE__);
            }
            if (outputWs.empty() && userOutputWs.empty() && guiW == nullptr
                && threadManagerMode != ThreadManagerMode::Asynchronous
                && threadManagerMode != ThreadManagerMode::AsynchronousOut)
            {
                error("No output selected.", __LINE__, __FUNCTION__, __FILE__);
            }

            // Thread Manager
            // Clean previous thread manager (avoid configure to crash the program if used more than once)
            threadManager.reset();
            unsigned long long threadId = 0ull;
            auto queueIn = 0ull;
            auto queueOut = 1ull;
            // After producer
            // ID generator (before any multi-threading or any function that requires the ID)
            const auto wIdGenerator = std::make_shared<WIdGenerator<TDatumsSP>>();
967 968 969 970 971 972 973 974 975 976 977 978
            // If custom user Worker and uses its own thread
            std::vector<TWorker> workersAux;
            if (!userPreProcessingWs.empty())
            {
                // If custom user Worker in its own thread
                if (userPreProcessingWsOnNewThread)
                    log("You chose to add your pre-processing function in a new thread. However, OpenPose will"
                        " add it in the same thread than the input frame producer.",
                        Priority::High, __LINE__, __FUNCTION__, __FILE__);
                workersAux = mergeVectors(workersAux, {userPreProcessingWs});
            }
            workersAux = mergeVectors(workersAux, {wIdGenerator});
G
gineshidalgo99 已提交
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
            // Scale & cv::Mat to OP format
            if (scaleAndSizeExtractorW != nullptr)
                workersAux = mergeVectors(workersAux, {scaleAndSizeExtractorW});
            if (cvMatToOpInputW != nullptr)
                workersAux = mergeVectors(workersAux, {cvMatToOpInputW});
            // cv::Mat to output format
            if (cvMatToOpOutputW != nullptr)
                workersAux = mergeVectors(workersAux, {cvMatToOpOutputW});

            // Producer
            // If custom user Worker and uses its own thread
            if (!userInputWs.empty() && userInputWsOnNewThread)
            {
                // Thread 0, queues 0 -> 1
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                threadManager.add(threadId, userInputWs, queueIn++, queueOut++);
                threadIdPP(threadId, multiThreadEnabled);
            }
            // If custom user Worker in same thread
            else if (!userInputWs.empty())
                workersAux = mergeVectors(userInputWs, workersAux);
            // If OpenPose producer (same thread)
            else if (datumProducerW != nullptr)
                workersAux = mergeVectors({datumProducerW}, workersAux);
            // Otherwise
            else if (threadManagerMode != ThreadManagerMode::Asynchronous
1005
                     && threadManagerMode != ThreadManagerMode::AsynchronousIn)
G
gineshidalgo99 已提交
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 1034 1035 1036 1037 1038 1039
                error("No input selected.", __LINE__, __FUNCTION__, __FILE__);
            // Thread 0 or 1, queues 0 -> 1
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
            threadManager.add(threadId, workersAux, queueIn++, queueOut++);
            // Increase thread
            threadIdPP(threadId, multiThreadEnabled);

            // Pose estimation & rendering
            // Thread 1 or 2...X, queues 1 -> 2, X = 2 + #GPUs
            if (!poseExtractorsWs.empty())
            {
                if (multiThreadEnabled)
                {
                    for (auto& wPose : poseExtractorsWs)
                    {
                        log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                        threadManager.add(threadId, wPose, queueIn, queueOut);
                        threadIdPP(threadId, multiThreadEnabled);
                    }
                    queueIn++;
                    queueOut++;
                    // Sort frames - Required own thread
                    if (poseExtractorsWs.size() > 1u)
                    {
                        const auto wQueueOrderer = std::make_shared<WQueueOrderer<TDatumsSP>>();
                        log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                        threadManager.add(threadId, wQueueOrderer, queueIn++, queueOut++);
                        threadIdPP(threadId, multiThreadEnabled);
                    }
                }
                else
                {
                    if (poseExtractorsWs.size() > 1)
                        log("Multi-threading disabled, only 1 thread running. All GPUs have been disabled but the"
G
gineshidalgo99 已提交
1040
                            " first one, which is defined by gpuNumberStart (e.g., in the OpenPose demo, it is set"
G
gineshidalgo99 已提交
1041 1042 1043 1044 1045 1046
                            " with the `--num_gpu_start` flag).", Priority::High);
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                    threadManager.add(threadId, poseExtractorsWs.at(0), queueIn++, queueOut++);
                }
            }
            // Assemble all frames from same time instant (3-D module)
G
gineshidalgo99 已提交
1047
            const auto wQueueAssembler = std::make_shared<WQueueAssembler<TDatums>>();
G
gineshidalgo99 已提交
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
            // 3-D reconstruction
            if (!poseTriangulationsWs.empty())
            {
                // Assemble frames
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                threadManager.add(threadId, wQueueAssembler, queueIn++, queueOut++);
                threadIdPP(threadId, multiThreadEnabled);
                // 3-D reconstruction
                if (multiThreadEnabled)
                {
                    for (auto& wPoseTriangulations : poseTriangulationsWs)
                    {
                        log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                        threadManager.add(threadId, wPoseTriangulations, queueIn, queueOut);
                        threadIdPP(threadId, multiThreadEnabled);
                    }
                    queueIn++;
                    queueOut++;
                    // Sort frames
                    if (poseTriangulationsWs.size() > 1u)
                    {
                        const auto wQueueOrderer = std::make_shared<WQueueOrderer<TDatumsSP>>();
                        log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                        threadManager.add(threadId, wQueueOrderer, queueIn++, queueOut++);
                        threadIdPP(threadId, multiThreadEnabled);
                    }
                }
                else
                {
                    if (poseTriangulationsWs.size() > 1)
                        log("Multi-threading disabled, only 1 thread running for 3-D triangulation.",
                            Priority::High);
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                    threadManager.add(threadId, poseTriangulationsWs.at(0), queueIn++, queueOut++);
                }
            }
            else
                postProcessingWs = mergeVectors({wQueueAssembler}, postProcessingWs);
            // Adam/IK step
            if (!jointAngleEstimationsWs.empty())
            {
                if (multiThreadEnabled)
                {
                    for (auto& wJointAngleEstimator : jointAngleEstimationsWs)
                    {
                        log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                        threadManager.add(threadId, wJointAngleEstimator, queueIn, queueOut);
                        threadIdPP(threadId, multiThreadEnabled);
                    }
                    queueIn++;
                    queueOut++;
                    // Sort frames
                    if (jointAngleEstimationsWs.size() > 1)
                    {
                        const auto wQueueOrderer = std::make_shared<WQueueOrderer<TDatumsSP>>();
                        log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                        threadManager.add(threadId, wQueueOrderer, queueIn++, queueOut++);
                        threadIdPP(threadId, multiThreadEnabled);
                    }
                }
                else
                {
                    if (jointAngleEstimationsWs.size() > 1)
                        log("Multi-threading disabled, only 1 thread running for joint angle estimation.",
                            Priority::High);
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                    threadManager.add(threadId, jointAngleEstimationsWs.at(0), queueIn++, queueOut++);
                }
            }
            // Post processing workers
            if (!postProcessingWs.empty())
            {
                // Combining postProcessingWs and outputWs
                outputWs = mergeVectors(postProcessingWs, outputWs);
                // // If I wanna split them
                // log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                // threadManager.add(threadId, postProcessingWs, queueIn++, queueOut++);
                // threadIdPP(threadId, multiThreadEnabled);
            }
            // If custom user Worker and uses its own thread
            if (!userPostProcessingWs.empty())
            {
                // If custom user Worker in its own thread
                if (userPostProcessingWsOnNewThread)
                {
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                    threadManager.add(threadId, userPostProcessingWs, queueIn++, queueOut++);
                    threadIdPP(threadId, multiThreadEnabled);
                }
                // If custom user Worker in same thread
                // Merge with outputWs
                else
                    outputWs = mergeVectors(outputWs, userPostProcessingWs);
            }
            // Output workers
            if (!outputWs.empty())
            {
                // Thread 4 or 5, queues 4 -> 5
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                threadManager.add(threadId, outputWs, queueIn++, queueOut++);
                threadIdPP(threadId, multiThreadEnabled);
            }
            // User output worker
            // Thread Y, queues Q -> Q+1
            if (!userOutputWs.empty())
            {
                if (userOutputWsOnNewThread)
                {
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                    threadManager.add(threadId, userOutputWs, queueIn++, queueOut++);
                    threadIdPP(threadId, multiThreadEnabled);
                }
                else
                {
                    log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                    threadManager.add(threadId-1, userOutputWs, queueIn++, queueOut++);
                }
            }
            // OpenPose GUI
            if (guiW != nullptr)
            {
                // Thread Y+1, queues Q+1 -> Q+2
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                threadManager.add(threadId, guiW, queueIn++, queueOut++);
1172 1173 1174
                // Saving 3D output
                if (videoSaver3DW != nullptr)
                    threadManager.add(threadId, videoSaver3DW, queueIn++, queueOut++);
G
gineshidalgo99 已提交
1175 1176 1177
                threadIdPP(threadId, multiThreadEnabled);
            }
            log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
1178 1179 1180 1181 1182 1183 1184
            // Setting maximum speed
            if (wFpsMax != nullptr)
            {
                log("", Priority::Low, __LINE__, __FUNCTION__, __FILE__);
                threadManager.add(threadId, wFpsMax, queueIn++, queueOut++);
                threadIdPP(threadId, multiThreadEnabled);
            }
G
gineshidalgo99 已提交
1185 1186 1187 1188 1189 1190
        }
        catch (const std::exception& e)
        {
            error(e.what(), __LINE__, __FUNCTION__, __FILE__);
        }
    }
G
gineshidalgo99 已提交
1191 1192
}

G
Gines 已提交
1193
#endif // OPENPOSE_WRAPPER_WRAPPER_AUXILIARY_HPP