跳转至

File ExampleMultiThreadMultiModels.cpp

Go to the documentation of this file.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
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
340
341
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#include <filesystem>
#include <iostream>
#include <string>
#include <thread>
#include <vector>

#include "ExampleMain.h"
#include "SaigeVisionAPI.h"
#include "SaigeVisionUtil.h"

namespace mul {

int clean_up_handles(std::vector<SaigeInferenceHandle>& handles,
                     std::vector<SaigeInferenceResult>& results) {
    int retval = 0;

    for (size_t i = 0; i < handles.size(); ++i) {
        retval = SaigeDestroyInferenceHandle(handles[i]);
        if (retval < 0) {
            std::cerr << "SaigeDestroyInferenceHandle() failed - " << SaigeStrError(retval)
                      << std::endl;
            // if you get this error, it's possible that the input pointer is not allocated
            // (nullptr).
            return retval;
        }
        retval = SaigeDestroyInferenceResult(results[i]);
        if (retval < 0) {
            std::cerr << "SaigeDestroyInferenceResult() failed - " << SaigeStrError(retval)
                      << std::endl;
            // if you get this error, it's possible that the input pointer is not allocated
            // (nullptr).
            return retval;
        }
    }

    return retval;
}

int run_multi_models() {
    std::string dataDir =
        get_env_var("SAIGE_HOME") + "/SaigeVision/engine/Examples/data/sfaw2023/images/test/";

    // 사용할 모델 목록
    std::vector<std::string> modelPathList = {dataDir + "../../models/seg_example.saigeseg",
                                              dataDir + "../../models/seg_example.saigeseg"};

    // 검사할 이미지 목록을 dataDir에서 불러온다.
    // C++17 이상에서만 동작
    std::vector<std::string> imagePaths;
    for (const auto& file : std::filesystem::recursive_directory_iterator(dataDir)) {
        if (file.is_regular_file() && file.path().extension() == ".png") {
            imagePaths.push_back(std::string(file.path().u8string()));
        }
    }

    int retval = 0;
    int verbosity = 2;
    int deviceIndex = 0;
    bool detailedTime = false;
    bool optimize = false;
    const char* oversizedImageHandlingMethod = SAIGE_DO_NOT_INSPECT;

    // Display config
    double overlayAlpha = 0.7;
    int waitkeyMilliSecond = 0;

    // 멀티스레드에서 검사하기 위해선 핸들과 결과 객체는 분리해야 한다.
    std::vector<SaigeInferenceHandle> handles(modelPathList.size(), nullptr);
    std::vector<SaigeInferenceResult> results(modelPathList.size(), nullptr);

    /***********************************************************
     *    1. 모델 파일 및 검사 결과 핸들 생성,
     *       Create handles for model files and inference results
     ***********************************************************/
    for (size_t i = 0; i < handles.size(); ++i) {
        SaigeHandleConfig config;
        config.inspectionSizeHeight = 2496;
        config.inspectionSizeWidth = 2496;
        unsigned int handleFlags = SAIGE_SET_INSPECTION_SIZE;
        if (optimize) {
            handleFlags |= SAIGE_OPTIMIZE_HANDLE;
        }

        retval = SaigeCreateInferenceHandle(&handles[i], kProjectTypeSEG, modelPathList[i].c_str(),
                                            deviceIndex, &config, handleFlags);

        if (retval < 0) {
            std::cerr << "SaigeCreateInferenceHandle failed - " << SaigeStrError(retval)
                      << std::endl;
            return retval;
        }

        retval = SaigeCreateInferenceResult(&results[i]);
        if (retval < 0) {
            std::cerr << "SaigeCreateInferenceResult failed - " << SaigeStrError(retval)
                      << std::endl;
            return retval;
        }
    }

    /***********************************************************
     *    2. 모델 정보 확인 (Optional)
     *        Check model information
     ***********************************************************/
    std::vector<SaigeModelInfo> modelInfos(modelPathList.size());
    std::cout << SaigeGetModuleVersion() << std::endl;

    for (size_t i = 0; i < handles.size(); ++i) {
        std::cout << "\n\n===============================" << std::endl;
        std::cout << "Model " << i << std::endl;
        retval = SaigeGetModelInfo(handles[i], &modelInfos[i]);
        if (retval < 0) {
            std::cerr << "SaigeGetModelInfo() failed - " << SaigeStrError(retval) << std::endl;
        } else if (verbosity >= 1) {
            std::cout << "[Segmentation Model Info]" << std::endl;
            std::cout << "Network Type: " << modelInfos[i].networkType << std::endl;
            std::cout << "Number of Classes: " << modelInfos[i].numOfClasses << std::endl;

            for (auto i = 0; i < modelInfos[i].numOfClasses; ++i) {
                uint8_t red, green, blue;
                SaigeColorCodeToRGB(modelInfos[i].classColors[i], &red, &green, &blue);
                std::cout << modelInfos[i].classNames[i] << ": color RGB(" << (int)red << ", "
                          << (int)green << ", " << (int)blue << ") - "
                          << (modelInfos[i].classIsNg[i] ? "NG" : "OK") << std::endl;
            }
            std::cout << "Trained Developer Version: " << modelInfos[i].developerVersion
                      << std::endl;
            std::cout << "Server Version: " << modelInfos[i].serverVersion << std::endl;
            std::cout << "Module Version: " << modelInfos[i].moduleVersion << std::endl;
            std::cout << "TrainingTimeStarted: " << modelInfos[i].trainingTimeStarted << std::endl;
            std::cout << "TrainingTimeCompleted: " << modelInfos[i].trainingTimeCompleted
                      << std::endl;
            std::cout << "TrainingTimeElapsed: " << modelInfos[i].trainingTimeElapsed << std::endl;
            std::cout << "UsedGpuName: " << modelInfos[i].usedGpuName << std::endl;
            std::cout << "Number of Train Images: " << modelInfos[i].numOfTrainImages << std::endl;
            std::cout << "Number of Validation Images: " << modelInfos[i].numOfValidationImages
                      << std::endl;
            std::cout << "Number of Iterations: " << modelInfos[i].numOfIterations << std::endl;
            std::cout << "ROI Info" << std::endl
                      << "- ROI Mode: " << modelInfos[i].roiInfo.roiMode << std::endl
                      << "- ROI LTRB Ratio: " << modelInfos[i].roiInfo.left << ", "
                      << modelInfos[i].roiInfo.top << ", " << modelInfos[i].roiInfo.right << ", "
                      << modelInfos[i].roiInfo.bottom << std::endl;
            std::cout << "Resize Factor: " << modelInfos[i].resizeFactor << std::endl;
            std::cout << "Crop Size (W, H): (" << modelInfos[i].cropSizeWidth << ", "
                      << modelInfos[i].cropSizeHeight << ")" << std::endl;
            if (modelInfos[i].roiInfo.blindMask != nullptr) {
                // show blind mask
                SaigeShowImage(modelInfos[i].roiInfo.blindMask,
                               modelInfos[i].roiInfo.blindMaskWidth,
                               modelInfos[i].roiInfo.blindMaskHeight, 1, SaigeImageType::SV_U8,
                               false, true, 255.0, 0);
            }
        }
    }

    /***********************************************************
     *    3. 검사 옵션 확인 및 수정 (Optional)
     *        Check inference options and set new values
     ***********************************************************/
    std::vector<SaigeInferenceOption> options(modelPathList.size());

    for (size_t i = 0; i < handles.size(); ++i) {
        std::cout << "\n\n===============================" << std::endl;
        std::cout << "Model " << i << std::endl;
        do {
            // Get Module Info 실패 시 검사옵션 확인 불가
            if (retval < 0) {
                break;
            }

            retval = SaigeGetInferenceOption(handles[i], &options[i]);
            if (retval < 0) {
                std::cerr << "SaigeGetInferenceOption() failed - " << SaigeStrError(retval)
                          << std::endl;
                clean_up_handles(handles, results);
                return retval;
            }
            if (detailedTime) {
                options[i].calcTime = true;
                retval = SaigeSetInferenceOption(handles[i], &options[i], SAIGE_SET_CALC_TIME);
                if (retval < 0) {
                    std::cerr << "SaigeSetInferenceOption() failed - " << SaigeStrError(retval)
                              << std::endl;
                    clean_up_handles(handles, results);
                    return retval;
                }
            }
            options[i].oversizedImageHandling = oversizedImageHandlingMethod;
            retval = SaigeSetInferenceOption(handles[i], &options[i],
                                             SAIGE_SET_OVERSIZED_IMAGE_HANDLING);
            if (retval < 0) {
                std::cerr << "SaigeSetInferenceOption() failed - " << SaigeStrError(retval)
                          << std::endl;
                clean_up_handles(handles, results);
                return retval;
            }
            if (verbosity >= 3) {
                options[i].calcMask = true;
                options[i].calcScoremap = true;
                options[i].calcObjectAreaAndApplyThreshold = true;
                options[i].calcObjectScoreAndApplyThreshold = true;
                unsigned int flags = SAIGE_SET_CALC_SCOREMAP | SAIGE_SET_CALC_MASK |
                                     SAIGE_SET_CALC_OBJECT_AREA_AND_APPLY_THRESHOLD |
                                     SAIGE_SET_CALC_OBJECT_SCORE_AND_APPLY_THRESHOLD;
                retval = SaigeSetInferenceOption(handles[i], &options[i], flags);
                if (retval < 0) {
                    std::cerr << "SaigeSetInferenceOption() failed - " << SaigeStrError(retval)
                              << std::endl;
                    clean_up_handles(handles, results);
                    return retval;
                }

                /*
                // 추론옵션 변경
                options[i].objectAreaThresholdPerClass[1] = 500;
                options[i].objectAreaThresholdPerClass[2] = 500;
                flags = SAIGE_SET_OBJECT_AREA_THRESHOLD;
                retval = SaigeSetInferenceOption(handles[i], &options[i], flags);
                if (retval < 0) {
                    std::cerr << "SaigeSetInferenceOption() failed - " << SaigeStrError(retval)
                              << std::endl;
                    clean_up_handles(handles, results);
                    return retval;
                }
                options[i].objectScoreThresholdPerClass[1] = 200.0;
                options[i].objectScoreThresholdPerClass[2] = 200.0;
                flags = SAIGE_SET_OBJECT_SCORE_THRESHOLD;
                retval = SaigeSetInferenceOption(handles[i], &options[i], flags);
                if (retval < 0) {
                    std::cerr << "SaigeSetInferenceOption() failed - " << SaigeStrError(retval)
                              << std::endl;
                    clean_up_handles(handles, results);
                    return retval;
                }
                options[i].objectBoundaryThresholdPerClass[1] = 150;
                options[i].objectBoundaryThresholdPerClass[2] = 150;
                flags = SAIGE_SET_OBJECT_BOUNDARY_THRESHOLD;
                retval = SaigeSetInferenceOption(handles[i], &options[i], flags);
                if (retval < 0) {
                    std::cerr << "SaigeSetInferenceOption() failed - " << SaigeStrError(retval)
                              << std::endl;
                    clean_up_handles(handles, results);
                    return retval;
                }
                */
            }
            if (verbosity >= 1) {
                std::cout.precision(17);

                std::cout << "[Segmentation Inference Options]" << std::endl;
                std::cout << "Calc Time: " << (options[i].calcTime ? "True" : "False") << std::endl;
                std::cout << "Batch Size: " << options[i].batchSize << std::endl;
                std::cout << "Inspection Size W, H: (" << options[i].inspectionSizeWidth << ", "
                          << options[i].inspectionSizeHeight << ")" << std::endl;
                std::cout << "Oversized Image Handling: " << options[i].oversizedImageHandling
                          << std::endl;
                std::cout << "Calc Mask: " << (options[i].calcMask ? "True" : "False") << std::endl;
                std::cout << "Calc Scoremap: " << (options[i].calcScoremap ? "True" : "False")
                          << std::endl;
                std::cout << "Calc Object: " << (options[i].calcObject ? "True" : "False")
                          << std::endl;
                std::cout << "Object Boundary Threshold Per Class: (";
                for (int i = 0; i < modelInfos[i].numOfClasses; ++i) {
                    std::cout << options[i].objectBoundaryThresholdPerClass[i] << ", ";
                }
                std::cout << ")" << std::endl;
                std::cout << "Calc Object Score and Apply Threshold: "
                          << (options[i].calcObjectScoreAndApplyThreshold ? "True" : "False")
                          << std::endl;
                std::cout << "Calc Object Area and Apply Threshold: "
                          << (options[i].calcObjectAreaAndApplyThreshold ? "True" : "False")
                          << std::endl;
                std::cout << "Object Area Threshold Per Class: (";
                for (int i = 0; i < modelInfos[i].numOfClasses; ++i) {
                    std::cout << options[i].objectAreaThresholdPerClass[i] << ", ";
                }
                std::cout << ")" << std::endl;

                std::cout << "Score Threshold Per Class: (";
                for (int i = 0; i < modelInfos[i].numOfClasses; ++i) {
                    std::cout << options[i].objectScoreThresholdPerClass[i] << ", ";
                }
                std::cout << ")" << std::endl;
            }
        } while (false);
    }

    /***********************************************************
     *    4. 이미지 검사하기, Inspect images
     *       이미지 사이즈는 같다고 가정한다.
     ***********************************************************/
    std::vector<std::thread> threads{};

    for (size_t i = 0; i < handles.size(); ++i) {
        threads.push_back(std::thread([verbosity, detailedTime, overlayAlpha, waitkeyMilliSecond,
                                       imagePaths, handle = handles[i], result = results[i],
                                       modelInfo = &modelInfos[i], modelNum = i] {
            int retval = 0;
            int h = 0, w = 0, c = 0, type = -1;
            int nbatch = 1;
            unsigned char* ucImageData = nullptr;
            std::vector<long long> inferenceTimes;
            std::string outputStr;
            for (auto i = 0; i < imagePaths.size(); ++i) {
                outputStr.clear();

                // 이미지 데이터 메모리를 해제합니다. (루프일관성)
                if (ucImageData != nullptr) {
                    retval = SaigeFreeImageData(ucImageData);
                    if (retval < 0) {
                        std::cerr << "SaigeFreeImageData() Failed - " << SaigeStrError(retval)
                                  << std::endl;
                    }
                    ucImageData = nullptr;
                }
                // 이미지 데이터를 로드합니다.
                ucImageData =
                    (unsigned char*)SaigeGetImageData(imagePaths[i].c_str(), &w, &h, &c, &type);
                if (ucImageData == nullptr) {
                    std::cerr << "SaigeGetImageData() failed - " << imagePaths[i] << std::endl;
                    continue;
                }

                /***********************************************************
                 *    4-1. 검사 함수 호출하기, Call Infer API
                 ***********************************************************/
                if (verbosity >= 2) {
                    outputStr += std::string("\n================================\n") +
                                 "Model: " + std::to_string(modelNum) + "\n" +
                                 "(Start): Infer From Image: " + imagePaths[i] + "\n---\n";
                }
                unsigned int imageFlag = SaigeConvertImageType(c, type);
                retval = SaigeInferFromByteArray(handle, (const unsigned char*)ucImageData, w, h,
                                                 imageFlag, result);
                if (retval < 0) {
                    std::cerr << "SaigeInferFromByteArray() failed - " << SaigeStrError(retval)
                              << std::endl;
                    continue;
                }

                /***********************************************************
                 *    4-2. 검사 결과 받아오기, Retrieve inference results
                 ***********************************************************/
                int numSegObj;
                unsigned char *mask, *scoremap;
                long long imreadTime, inferenceTime, postProcessingTime;
                std::vector<SaigeSegmentedObject> segObjs;

                // DEFAULT (segObjs)
                retval = SaigeGetInferenceResultNumOfSegmentedObjects(result, &numSegObj);
                if (retval < 0) {
                    std::cerr << "SaigeGetInferenceResultNumOfSegmentedObjects() failed - "
                              << SaigeStrError(retval) << std::endl;
                    return retval;
                }
                segObjs.resize(numSegObj);
                if (numSegObj > 0) {
                    retval = SaigeGetInferenceResultSegmentedObjects(result, segObjs.data());
                    if (retval < 0) {
                        std::cerr << "SaigeGetInferenceResultSegmentedObjects() failed - "
                                  << SaigeStrError(retval) << std::endl;
                        return retval;
                    }
                }
                retval = SaigeGetInferenceResultInspectionTime(result, &imreadTime, &inferenceTime,
                                                               &postProcessingTime);
                if (retval < 0) {
                    std::cerr << "SaigeGetInferenceResultInspectionTime() failed - "
                              << SaigeStrError(retval) << std::endl;
                    return retval;
                }
                inferenceTimes.push_back(imreadTime + inferenceTime + postProcessingTime);
                if (verbosity >= 2) {
                    outputStr += "Success to get segmented objects\n";
                }

                if (verbosity >= 3) {
                    for (int i_seg = 0; i_seg < numSegObj; ++i_seg) {
                        outputStr += std::string("[Segmented Object (") + std::to_string(i_seg) +
                                     ")]\n" + "  - Area: " + std::to_string(segObjs[i_seg].area) +
                                     "  - Score: " + std::to_string(segObjs[i_seg].score) +
                                     "  - Class: " + std::to_string(segObjs[i_seg].score) + " " +
                                     modelInfo->classNames[segObjs[i_seg].classIndex] + "\n";
                    }
                    retval = SaigeGetInferenceResultMask(result, &mask);
                    if (retval < 0) {
                        std::cerr << "SaigeGetInferenceResultMask() failed - "
                                  << SaigeStrError(retval) << std::endl;
                        return retval;
                    }
                    outputStr += std::string("[Mask]\n");
                    std::vector<int> numOfPixels(modelInfo->numOfClasses, 0);
                    for (int j = 0; j < h; ++j) {
                        for (int k = 0; k < w; ++k) {
                            numOfPixels[mask[j * w + k]]++;
                        }
                    }
                    for (int i = 0; i < modelInfo->numOfClasses; ++i) {
                        outputStr += std::string("Number of pixels of class ") + std::to_string(i) +
                                     ": " + std::to_string(numOfPixels[i]) + "\n";
                    }
                    retval = SaigeGetInferenceResultScoremapSEG(result, &scoremap);
                    if (retval < 0) {
                        std::cerr << "SaigeGetInferenceResultScoremapSEG() failed - "
                                  << SaigeStrError(retval) << std::endl;
                        return retval;
                    }
                }
                if (verbosity >= 2) {
                    if (detailedTime) {
                        outputStr +=
                            std::string("---\n(End) Image Read, Infer, Postprocess Times (ms): (") +
                            std::to_string(imreadTime) + ", " + std::to_string(inferenceTime) +
                            ", " + std::to_string(postProcessingTime) + ")\n";
                    } else {
                        outputStr += std::string("---\n(End) Inspection Time: ") +
                                     std::to_string(inferenceTime) + " ms\n";
                    }
                }

                std::cout << outputStr << std::endl;
            }

            if (verbosity >= 1) {
                long long totalInferenceTime = 0;
                long long maxInferenceTime = 0;
                for (auto time : inferenceTimes) {
                    totalInferenceTime += time;
                    if (time > maxInferenceTime) {
                        maxInferenceTime = time;
                    }
                }
                outputStr.clear();
                outputStr += std::string("\n===========================\n") +
                             "Model: " + std::to_string(modelNum) + "\n" +
                             "Total Elapsed Time: " + std::to_string(totalInferenceTime) + " ms\n" +
                             "Average Elapsed Time Per Image: " +
                             std::to_string(totalInferenceTime / inferenceTimes.size()) + " ms\n" +
                             "Max Elapsed Time: " + std::to_string(maxInferenceTime) + " ms";
                std::cout << outputStr << std::endl;
            }
            if (ucImageData != nullptr) {
                retval = SaigeFreeImageData(ucImageData);
                if (retval < 0) {
                    std::cerr << "SaigeFreeImageData() Failed - " << SaigeStrError(retval)
                              << std::endl;
                }
                ucImageData = nullptr;
            }
            return 0;
        }));
    }

    for (auto& th : threads) {
        th.join();
    }

    /***********************************************************
     *    5. 핸들 파괴, Destruct handles
     ***********************************************************/
    clean_up_handles(handles, results);

    return 0;
}

}  // namespace mul