SaigeVision C/C++  1.4.7
SaigeVision API document for C/C++
ExampleSuperResolution+SegRuntime.cpp

This is an example of how to run super resolution before seg module. More details about this example.

#include "SRUtils.h"
/* define this variable when user want to use new score threshold other than preset values. */
//#define SR_USE_NEW_SCORE_THRESHOLD
/* define this variable when user want to use new pixel size threshold other than preset values. */
//#define SR_USE_NEW_PIXEL_SIZE_THRESHOLD
/* define this variable when user want filter contours smaller than a threshold of pixel size by calculating appoximate contour sizes.*/
#define SR_FILTER_OBJECTS_BY_APPROXIMATE_SIZE
/* define this variable when user want filter contours smaller than a threshold of pixel size by calculating appoximate contour sizes.*/
//#define SR_FILTER_OBJECTS_BY_EXACT_SIZE
/* define this variable when user want to get cropped image of segmented objects.*/
//#define SR_CROP_AND_STORE_SEGMENTED_OBJECT
/* define this variable when user want to get scores(average, min, max) of semgmented objects.*/
//#define SR_GET_SCORES_OF_SEGMENTED_OBJECT
/* define this variable when user want to get average color(in BGR order) of semgmented objects.*/
//#define SR_GET_AVERAGE_COLOR_OF_SEGMENTED_OBJECT
/* define this variable when user want to limit the forward time of classfication algorithm. */
//#define SR_USE_FORWARD_TIME_LIMIT
int main()
{
std::wstring data_dir = L"../../../examples/data";
// trained model path
std::wstring trainedModelPathSeg = data_dir + L"/models/pcb_sample_model.srSeg";
std::wstring trainedModelPathSupRes = data_dir + L"/models/pcb_supres_sample_model.srSupRes";
// image paths to classify
std::vector<std::wstring> imagePaths(3);
imagePaths[0] = data_dir + L"/images/PCB_SupRes/val/low/Image-7.png";
imagePaths[1] = data_dir + L"/images/PCB_SupRes/val/low/Image-8.png";
imagePaths[2] = data_dir + L"/images/PCB_SupRes/val/low/Image-9.png";
/***********************************************************
* 0. 이미지 인풋 타입 설정
* inputImageType -
* ImageFilePathMultiByteChar: from file path (multi byte char)
* ImageFilePathWideChar: from file path (wide char)
* UCGrayImage: from memory(8bit unsigned char gray image)
* UCColorImage: from memory(8bit unsigned char color image)
* UIColorImage: from memory(32bit unsigned int color image)
***********************************************************/
//eSRInputImageType inputImageType = eSRInputImageType::ImageFilePathMultiByteChar;
//eSRInputImageType inputImageType = eSRInputImageType::ImageFilePathWideChar;
eSRInputImageType inputImageType = eSRInputImageType::UCGrayImage;
//eSRInputImageType inputImageType = eSRInputImageType::UCColorImage;
//eSRInputImageType inputImageType = eSRInputImageType::UIColorImage;
unsigned char* ucImageData = nullptr; // unsigned char image data
unsigned char* ucImageDataSupRes = nullptr; // unsigned char image data after super resolution
unsigned int* uiImageData = nullptr; // unsigned int image data
/***********************************************************
* 0-1. 정보 띄우기 단계 설정 (Verbosity)
* verbosity -
* 0: only warning
* 1: warning + model info
* 2: warning + model info + result info
* 3: warning + model info + result info + image display
* overlayAlpha - display 이미지 = 원본 이미지 * overlayAlpha + segmentation 라벨 * (1 - overlayAlpha)
* displayTime - 결과 이미지 display 하는 시간 (milliseconds)
* resizeFactor - 결과 이미지 display 하는 스케일 (display 크기 = 원본 크기 * resizeFactor)
***********************************************************/
int verbosity = 3;
double overlayAlpha = 0.7;
int displayTime = 100;
double resizeFactor = 1;
/***********************************************************
* 0-2. GPU 번호 설정
* gpuIndex - 사용하고자 하는 gpu의 번호
* Multi GPU 가 가능한 License의 경우에 한하여 gpuIndex를
* 0~3까지 설정해 줄 수 있다. 아닌 경우 gpuIndex는 0을 사용하여야 한다.
***********************************************************/
int gpuIndex = 0;
/***********************************************************
* 0-3. Super Resolution ROI 적용 여부 설정
***********************************************************/
bool applyROIOfSegToSupRes = true;
/***********************************************************
* 0-4. Segmentation 검사 방법 설정
***********************************************************/
/***********************************************************
* 1. 모델 파일 및 검사 결과 handle 생성,
* Create handles for model files and inspection results
***********************************************************/
SupResTestHandle supResTestHandle = SR_CreateSupResTestHandleByWideCharPath(trainedModelPathSupRes.c_str());
if (supResTestHandle == nullptr)
{
std::wcout << "Saige Vision failed: Please check the file path of super resolution model." << std::endl;
}
SegTestHandle segHandle = SR_CreateSegTestHandleByWideCharPath(trainedModelPathSeg.c_str());
if (segHandle == nullptr)
{
std::wcout << "Saige Vision failed: Please check the file path of segmentation model." << std::endl;
}
/***********************************************************
* 2. 클래스 정보 확인 (Optional)
* Check class information
***********************************************************/
// Print segmentation Test Parameters() by calling one fuctions
srStatus = SR_PrintSegTestParametersWithoutBG(segHandle);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the handle is not created.
return -1;
}
int numberOfClassesOutput = 0;
int maxStrLenOfClassName = 0;
// Get the number of classes
srStatus = SR_GetSegTestNumberOfClassesWithoutBG(segHandle, &numberOfClassesOutput);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that input pointer is not allocated (nullptr).
return -1;
}
// Get the maximum length of class names
srStatus = SR_GetSegTestMaxStrLenOfClassName(segHandle, &maxStrLenOfClassName);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that input pointer is not allocated (nullptr).
return -1;
}
std::vector<std::string> classNames(numberOfClassesOutput);
std::vector<std::wstring> wClassNames(numberOfClassesOutput);
std::vector<int> classColorsOutput(numberOfClassesOutput);
char* classNameOutput = new char[maxStrLenOfClassName];
wchar_t* wClassNameOutput = new wchar_t[maxStrLenOfClassName];
for (int i = 0; i < numberOfClassesOutput; i++)
{
// Get a color of single class
srStatus = SR_GetSegTestOneClassColorByIdxWithoutBG(segHandle, i, &(classColorsOutput[i]));
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input index is out of bound(# of classes) or input pointer is not allocated (nullptr).
return -1;
}
// Get a name of single class by multi byte char (char*)
srStatus = SR_GetSegTestOneClassNameWithMultiByteCharByIdxWithoutBG(segHandle, i, classNameOutput);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input index is out of bound(# of classes) or input pointer is not allocated (nullptr).
return -1;
}
// Get a name of single class by wide char (wchar_t*)
srStatus = SR_GetSegTestOneClassNameWithWideCharByIdxWithoutBG(segHandle, i, wClassNameOutput);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input index is out of bound(# of classes) or input pointer is not allocated (nullptr).
return -1;
}
classNames[i] = classNameOutput;
wClassNames[i] = wClassNameOutput;
}
delete[] classNameOutput;
delete[] wClassNameOutput;
/***********************************************************
* 3. 검사 옵션 확인 및 수정 (Optional)
* Check inspection options and set new values
***********************************************************/
/*
학습에서 사용한 이미지 크기와 검사에서 사용하는 이미지 크기가 다를 경우 아래 함수를 호출하여
검사 이미지 사이즈에 맞게 최대 검사 사이즈를 설정하여야 합니다.
최대 검사 사이즈 보다 큰 이미지가 들어올 경우 최대 검사 사이즈로 리사이즈된 후 검사됩니다.
단 이 함수는 SR_LoadSegTestNetworkInGPU 함수를 호출하기 전 호출되어야 합니다.
SR_GetSegTestMaxInspectionSize 함수를 통해 현재 설정되어 있는 최대 검사 사이즈를 확인할 수 있습니다.
*/
/*
srStatus = SR_SetSegTestMaxInspectionSize(SegTestHandle handle, int maxInspectionHeight, int maxInspectionWidth, bool writeOnModel);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that SR_LoadSegTestNetwork is already called.
SR_DestroySegTestHandle(handle);
return -1;
}*/
std::vector<int> scoreThresholdOutput(numberOfClassesOutput);
std::vector<int> pixelSizeThresholdOutput(numberOfClassesOutput);
// Get the score threshold for each class
srStatus = SR_GetSegTestMinScoreThresholdWithoutBG(segHandle, scoreThresholdOutput.data());
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that input pointer is not allocated (nullptr).
return -1;
}
// Get the area threshold for each class
srStatus = SR_GetSegTestMinPixelSizeThresholdWithoutBG(segHandle, pixelSizeThresholdOutput.data());
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that input pointer is not allocated (nullptr).
return -1;
}
# ifdef SR_USE_NEW_SCORE_THRESHOLD
std::vector<int> scoreThreshold(numberOfClassesOutput);
for (int i = 0; i < numberOfClassesOutput; i++)
{
scoreThreshold[i] = 100; // Set the new score threshold for each class
}
srStatus = SR_SetSegTestMinScoreThresholdWithoutBG(handle, numberOfClassesOutput, scoreThreshold.data(), true);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
return -1;
}
#endif
# ifdef SR_USE_NEW_PIXEL_SIZE_THRESHOLD
std::vector<int> pixelSizeThreshold(numberOfClassesOutput);
for (int i = 0; i < numberOfClassesOutput; i++)
{
pixelSizeThreshold[i] = 200; // Set the new pixel-size threshold for each class
}
srStatus = SR_SetSegTestMinPixelSizeThresholdWithoutBG(handle, numberOfClassesOutput, pixelSizeThreshold.data(), true);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
return -1;
}
pixelSizeThresholdOutput = pixelSizeThreshold;
#endif
#if (!defined(SR_FILTER_OBJECTS_BY_EXACT_SIZE)) && (!defined(SR_FILTER_OBJECTS_BY_APPROXIMATE_SIZE))
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that handle is not created or filter mode is not appropriate.
return -1;
}
#endif
#ifdef SR_FILTER_OBJECTS_BY_EXACT_SIZE
// "SaigeVision Error: CANNOT USE FILTERING FUNCTION IN CURRENT OUTPUT MODE"
assert(outputMode == SR_ONE_CLASS_CV_CONTOUR_OUTPUT || outputMode == SR_MULTI_CLASS_CV_CONTOUR_OUTPUT);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that handle is not created or filter mode is not appropriate.
return -1;
}
#endif
#ifdef SR_FILTER_OBJECTS_BY_APPROXIMATE_SIZE
// "SaigeVision Error: CANNOT USE FILTERING FUNCTION IN CURRENT OUTPUT MODE"
assert(outputMode == SR_ONE_CLASS_CV_CONTOUR_OUTPUT || outputMode == SR_MULTI_CLASS_CV_CONTOUR_OUTPUT);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that handle is not created or filter mode is not appropriate.
return -1;
}
#endif
#ifdef SR_CROP_AND_STORE_SEGMENTED_OBJECT
int cropSize = 256;
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that handle is not created.
return -1;
}
#endif
#ifdef SR_GET_SCORES_OF_SEGMENTED_OBJECT
srStatus = SR_SetSegTestIsToCalcObjectScores(handle, true, true);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that handle is not created.
return -1;
}
#endif
#ifdef SR_GET_AVERAGE_COLOR_OF_SEGMENTED_OBJECT
srStatus = SR_SetSegTestIsToCalcAverageColor(handle, true, true);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that handle is not created.
return -1;
}
#endif
#ifdef SR_USE_FORWARD_TIME_LIMIT
float timeLimit = 1000; // milliseconds
srStatus = SR_SetSegTestForwardTimeLimitVariables(handle, timeLimit, true, true);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that handle is not created.
return -1;
}
#endif
#ifndef SR_USE_FORWARD_TIME_LIMIT
srStatus = SR_SetSegTestIsToUseForwardTimeLimit(segHandle, false, true);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that handle is not created.
return -1;
}
#endif
/***********************************************************
* 4. 메모리를 GPU 및 CPU에 할당합니다.
* Allocate GPU and CPU memory
***********************************************************/
srStatus = SR_LoadSupResTestNetworkInGPU(supResTestHandle, gpuIndex);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the inserted index is not applicable.
SR_DestroySupResTestHandle(supResTestHandle);
return -1;
}
srStatus = SR_LoadSegTestNetworkInGPU(segHandle, gpuIndex);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the inserted index is not applicable.
return -1;
}
if (applyROIOfSegToSupRes)
{
srStatus = SR_SetROIInfoFromSeg(supResTestHandle, segHandle);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the inserted index is not applicable.
return -1;
}
}
for (size_t i_img = 0; i_img < imagePaths.size(); i_img++)
{
int h = 0, w = 0;
if (inputImageType == eSRInputImageType::UIColorImage)
{
uiImageData = (unsigned int*)GetImageDataByInputImageType(imagePaths[i_img], inputImageType, h, w);
}
else
{
ucImageData = (unsigned char*)GetImageDataByInputImageType(imagePaths[i_img], inputImageType, h, w);
}
/***********************************************************
* 5. 초해상화 적용하기, Apply super resolution to an image
***********************************************************/
if (inputImageType == eSRInputImageType::ImageFilePathMultiByteChar) {
// Check if given image path(UNICODE) can be converted to ASCII CODE without any loss.
size_t sizeOfChar = 0;
size_t sizeOfWChar = wcslen(imagePaths[i_img].c_str());
size_t bufferSize = sizeOfWChar * 2;
std::vector<char> imagePathMB(bufferSize);
sizeOfChar = wcstombs(
imagePathMB.data(),
imagePaths[i_img].c_str(),
bufferSize
);
if (sizeOfChar != sizeOfWChar)
{
std::wcout << "Saige Vision FAILED: Wrong Image path" << imagePaths[i_img] << std::endl;
continue;
}
srStatus = SR_ApplySupResTestFromImageFile(supResTestHandle, imagePathMB.data(), supResTestResult);
}
else if (inputImageType == eSRInputImageType::ImageFilePathWideChar) {
srStatus = SR_ApplySupResTestFromImageFileByWideCharPath(supResTestHandle, imagePaths[i_img].c_str(), supResTestResult);
}
else if (inputImageType == eSRInputImageType::UCGrayImage) {
srStatus = SR_ApplySupResTestFrom8bitCharGrayArray(supResTestHandle, ucImageData, h, w, supResTestResult);
}
else if (inputImageType == eSRInputImageType::UCColorImage) {
srStatus = SR_ApplySupResTestFrom8bitCharColorArray(supResTestHandle, ucImageData, h, w, supResTestResult);
}
else if (inputImageType == eSRInputImageType::UIColorImage) {
srStatus = SR_ApplySupResTestFromUnsignedIntColorArray(supResTestHandle, uiImageData, h, w, supResTestResult);
}
else {
std::wcout << "Saige Vision failed: Super resolution can only be applied to UCGrayImage type." << std::endl;
srStatus = UNKNOWN_ERROR;
}
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input data is not loaded successfully.
if (verbosity >= 3)
{
imagePaths[i_img], "FAIL TO SUPER RESOLUTION", "Super Resolution Result", displayTime, resizeFactor);
}
continue; // jump to next image
}
long supResInferenceTimeOutput = 0;
long supResLoadImageTimeOutput = 0;
// Get the inspection time
srStatus = SR_GetSupResTestInferenceTime(supResTestResult, &supResInferenceTimeOutput);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
continue; // jump to next image
}
// Get the image-loading time
srStatus = SR_GetSupResTestLoadImageTime(supResTestResult, &supResLoadImageTimeOutput);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
continue; // jump to next image
}
// Display and draw
if (verbosity >= 2)
{
std::cout << std::endl << "====== Super resolution Result ======" << std::endl;
std::wcout << imagePaths[i_img] << std::endl;
std::cout << " - Image Loading time: " << supResLoadImageTimeOutput << std::endl;
std::cout << " - Inspection time: " << supResInferenceTimeOutput << std::endl;
}
int heightSupRes = 0, widthSupRes = 0;
srStatus = SR_GetSupResTestResultImageSize(supResTestResult, &heightSupRes, &widthSupRes);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
continue; // jump to next image
}
ucImageDataSupRes = new unsigned char[heightSupRes * widthSupRes];
srStatus = SR_GetSupResTestResultImage(supResTestResult, ucImageDataSupRes);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
continue; // jump to next image
}
if (ucImageData != nullptr)
{
delete[] ucImageData;
}
if (uiImageData != nullptr)
{
delete[] uiImageData;
}
/***********************************************************
* 6. 이미지 검사하기, Inspect images
***********************************************************/
if (inputImageType == eSRInputImageType::ImageFilePathWideChar ||
inputImageType == eSRInputImageType::ImageFilePathMultiByteChar)
{
// Get dimension of input image to draw results later..
srStatus = SR_GetSupResTestResultImageSize(supResTestResult, &h, &w);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
continue; // jump to next image
}
}
// Super resolution 적용된 이미지는 1채널 그레이 이미지이기 때문에
// 반드시 아래 함수를 사용하여 segmentation을 적용해야 합니다.
srStatus = SR_ApplySegTestFrom8bitCharGrayArray(segHandle, ucImageDataSupRes, h, w, segTestResult, outputMode);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input data is not loaded successfully.
if (verbosity >= 3)
{
DisplayFailedImageOnCVWindow(imagePaths[i_img], "FAIL TO segment", "segmentation Result", displayTime, resizeFactor);
}
continue; // jump to next image
}
/***********************************************************
* 7. 검사 결과 받아오기, Retrieve inspection results
***********************************************************/
if (inputImageType == eSRInputImageType::ImageFilePathWideChar || inputImageType == eSRInputImageType::ImageFilePathMultiByteChar)
{
// Get dimension of input image to draw results later..
srStatus = SR_GetSegTestResultOriginalImageSize(segTestResult, &w, &h);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
continue; // jump to next image
}
}
long inspectionTimeOutput = 0, loadImageTimeOutput = 0;
// Get the inspection time
srStatus = SR_GetSegTestInspectionTime(segTestResult, &inspectionTimeOutput);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
continue; // jump to next image
}
// Get the image-loading time
srStatus = SR_GetSegTestLoadImageTime(segTestResult, &loadImageTimeOutput);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
continue; // jump to next image
}
/* Getting output matrix is optional when output mode is SR_ONE_CLASS_CV_CONTOUR_OUTPUT or SR_MULTI_CLASS_CV_CONTOUR_OUTPUT.
* Output matrix 를 가져오는 과정은 SR_ONE_CLASS_CV_CONTOUR_OUTPUT or SR_MULTI_CLASS_CV_CONTOUR_OUTPUT 두 모드일 경우 optional 입니다.
*/
int matrixChannelOutput = 0, matrixSizeOutput = 0;
std::vector<unsigned char> outputMatrix;
if (outputMode == SR_ONE_CLASS_MATRIX_OUTPUT ||
outputMode == SR_MULTI_CLASS_HEATMAP_OUTPUT)
{
// Get the dimension of output matrix
srStatus = SR_GetSegTestOutputMatrixSizeInfo(segTestResult, &matrixChannelOutput, &matrixSizeOutput);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
continue; // jump to next image
}
outputMatrix.resize(matrixSizeOutput);
// Get the data of output matrix (score matrix)
srStatus = SR_GetSegTestOutputMatrix(segTestResult, matrixSizeOutput, outputMatrix.data());
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input's size(matrixSizeOutput) does not match the result's or input pointer is not allocated (nullptr).
continue; // jump to next image
}
}
// Display and draw
if (verbosity >= 2)
{
std::cout << "====== segmentation Test Result ======" << std::endl;
std::wcout << imagePaths[i_img] << std::endl;
std::cout << " - Image width, height: " << w << ", " << h << std::endl;
std::cout << " - Image Loading time: " << loadImageTimeOutput << std::endl;
std::cout << " - Inspection time: " << inspectionTimeOutput << std::endl;
}
// Get Segmented objects
// segmented object after filtering (# of classes x # of objects)
std::vector<SR_SegmentedObject> segmentedObject;
// deleted object after filtering (# of classes x # of objects)
std::vector<SR_SegmentedObject> deletedObject;
{
int nSegmentedObjects = 0;
srStatus = SR_GetSegTestNumberOfSegmentedObjects(segTestResult, &nSegmentedObjects);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the segTestResult is not created (nullptr).
continue; // jump to next image
}
segmentedObject.resize(nSegmentedObjects);
srStatus = SR_GetSegTestSegmentedObjects(segTestResult, segmentedObject.data());
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the segTestResult is not created (nullptr).
continue; // jump to next image
}
// if user want to check the deleted objects by filtering, call this functions.
int nDeletedObjects = 0;
srStatus = SR_GetSegTestNumberOfDeletedObjects(segTestResult, &nDeletedObjects);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the segTestResult is not created (nullptr).
continue; // jump to next image
}
deletedObject.resize(nDeletedObjects);
srStatus = SR_GetSegTestDeletedObjects(segTestResult, deletedObject.data());
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the segTestResult is not created (nullptr).
continue; // jump to next image
}
if (verbosity >= 2)
{
std::cout << " - the number of deleted objects: " << deletedObject.size() << std::endl;
}
}
if (verbosity >= 3)
{
cv::Mat image = cv::Mat();
image = cv::Mat(h, w, CV_8UC1, ucImageDataSupRes);
image = image.clone(); /* to prevent modifying raw data */
if (outputMode == SR_ONE_CLASS_MATRIX_OUTPUT || outputMode == SR_ONE_CLASS_CV_CONTOUR_OUTPUT)
{
if (image.channels() == 4)
{
cv::cvtColor(image, image, cv::COLOR_BGRA2BGR);
}
cv::Mat imageCheck = image.clone();
unsigned char* data = imageCheck.data;
if (outputMode == SR_ONE_CLASS_MATRIX_OUTPUT)
{
if (image.channels() == 1)
{
for (int i_pixel = 0; i_pixel < matrixSizeOutput; i_pixel++)
{
if (outputMatrix[i_pixel] > 0)
{
data[i_pixel] = outputMatrix[i_pixel];
}
}
}
else if (image.channels() == 3)
{
for (int i_pixel = 0; i_pixel < matrixSizeOutput; i_pixel++)
{
if (outputMatrix[i_pixel] > 0)
{
data[3 * i_pixel + 0] = 0;
data[3 * i_pixel + 1] = 0;
data[3 * i_pixel + 2] = outputMatrix[i_pixel];
}
}
}
}
else if (outputMode == SR_ONE_CLASS_CV_CONTOUR_OUTPUT)
{
cv::Scalar whiteScalar = cv::Scalar(255.0);
if (image.channels() == 1)
{
whiteScalar = cv::Scalar(255.0);
}
else if (image.channels() == 3)
{
whiteScalar = cv::Scalar(0, 0, 255.0);
}
for (int i_c = 0; i_c < segmentedObject.size(); i_c++)
{
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
convertSRSegmentedObjectToOpencvFormat(segmentedObject[i_c], contours, hierarchy);
cv::drawContours(imageCheck, contours, -1, whiteScalar, -1, 8, hierarchy);
}
}
cv::Mat finalUnifiedImage;
double beta = 1.0 - overlayAlpha;
double gamma = 0;
cv::addWeighted(image, overlayAlpha, imageCheck, beta, gamma, finalUnifiedImage);
cv::namedWindow("Segmentation Result", cv::WINDOW_NORMAL);
cv::resizeWindow("Segmentation Result", w * resizeFactor, h * resizeFactor);
cv::imshow("Segmentation Result", finalUnifiedImage);
cv::waitKey(displayTime);
}
else if (outputMode == SR_MULTI_CLASS_MATRIX_OUTPUT || outputMode == SR_MULTI_CLASS_HEATMAP_OUTPUT || outputMode == SR_MULTI_CLASS_CV_CONTOUR_OUTPUT)
{
if (image.channels() == 4)
{
cv::cvtColor(image, image, cv::COLOR_BGRA2BGR);
}
else if (image.channels() == 1)
{
cv::cvtColor(image, image, cv::COLOR_GRAY2BGR);
}
cv::Mat imageCheck = image.clone();
if (outputMode == SR_MULTI_CLASS_MATRIX_OUTPUT || outputMode == SR_MULTI_CLASS_HEATMAP_OUTPUT)
{
unsigned char* data = imageCheck.data;
for (int i_pixel = 0; i_pixel < w * h; i_pixel++)
{
int maxVal = 0;
int channel = 0;
for (int c = 0; c < numberOfClassesOutput; c++)
{
if (outputMatrix[i_pixel + c * w * h] > maxVal)
{
maxVal = outputMatrix[i_pixel + c * w * h];
channel = c;
}
}
unsigned char* tmp = (unsigned char*)(&classColorsOutput[channel]);
int b = 0, g = 0, r = 0;
std::memcpy(&b, tmp, 1);
std::memcpy(&g, tmp + 1, 1);
std::memcpy(&r, tmp + 2, 1);
if (maxVal != 0) // else: background
{
data[3 * i_pixel + 0] = b * (maxVal / 255.0);
data[3 * i_pixel + 1] = g * (maxVal / 255.0);
data[3 * i_pixel + 2] = r * (maxVal / 255.0);
}
}
}
else if (outputMode == SR_MULTI_CLASS_CV_CONTOUR_OUTPUT)
{
for (int i_c = 0; i_c < segmentedObject.size(); i_c++)
{
unsigned char* tmp = (unsigned char*)(&classColorsOutput[segmentedObject[i_c].classIdx]);
int b = 0, g = 0, r = 0;
std::memcpy(&b, tmp, 1);
std::memcpy(&g, tmp + 1, 1);
std::memcpy(&r, tmp + 2, 1);
cv::Scalar overlayScalar = cv::Scalar(b, g, r);
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
convertSRSegmentedObjectToOpencvFormat(segmentedObject[i_c], contours, hierarchy);
cv::drawContours(imageCheck, contours, -1, overlayScalar, -1, 8, hierarchy);
}
}
cv::Mat finalUnifiedImage;
double beta = 1.0 - overlayAlpha;
double gamma = 0.0;
cv::addWeighted(image, overlayAlpha, imageCheck, beta, gamma, finalUnifiedImage);
cv::namedWindow("Segmentation Result", cv::WINDOW_NORMAL);
cv::resizeWindow("Segmentation Result", w * resizeFactor, h * resizeFactor);
cv::imshow("Segmentation Result", finalUnifiedImage);
cv::waitKey(displayTime);
#ifdef SR_CROP_AND_STORE_SEGMENTED_OBJECT
for (int i_c = 0; i_c < segmentedObject.size(); i_c++)
{
if (segmentedObject[i_c].croppedImage != nullptr)
{
int dataType = CV_MAKETYPE(CV_8U, segmentedObject[i_c].croppedImageChannels);
cv::Mat croppedImage = cv::Mat(segmentedObject[i_c].croppedImageHeight, segmentedObject[i_c].croppedImageWidth, dataType, segmentedObject[i_c].croppedImage);
cv::namedWindow("Segmentation Cropped Image", cv::WINDOW_NORMAL);
cv::resizeWindow("Segmentation Cropped Image", croppedImage.size().width, croppedImage.size().height);
cv::imshow("Segmentation Cropped Image", croppedImage);
cv::waitKey(displayTime);
}
}
#endif
}
}
if (ucImageDataSupRes != nullptr)
{
delete[] ucImageDataSupRes;
}
}
/***********************************************************
* 8. Handle 파괴, Destruct handles
***********************************************************/
srStatus = SR_DeleteSupResTestResult(supResTestResult);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
return -1;
}
srStatus = SR_DestroySupResTestHandle(supResTestHandle);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
return -1;
}
srStatus = SR_DeleteSegTestResult(segTestResult);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
return -1;
}
srStatus = SR_DestroySegTestHandle(segHandle);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
return -1;
}
std::cout << "SaigeVision successfully completed, please press enter key to terminate" << std::endl;
std::cin.get();
return 0;
}
SR_ApplySupResTestFromUnsignedIntColorArray
eErrorType SR_ApplySupResTestFromUnsignedIntColorArray(SupResTestHandle handle, const unsigned int *imageData, const int height, const int width, SupResTestResult result)
SupResTestHandle 을 이용하여 초해상화를 수행합니다.
SR_SetSegTestModeOfFilteringByPixelSize
eErrorType SR_SetSegTestModeOfFilteringByPixelSize(SegTestHandle handle, eModeOfPixelSizeFilter modeOfFiltering, bool writeOnModelFile=true)
Set the mode of filtering by Segmentation's area threshold.
SR_SetSegTestMinPixelSizeThresholdWithoutBG
eErrorType SR_SetSegTestMinPixelSizeThresholdWithoutBG(SegTestHandle handle, int numOfClasses, int *areaThreshold, bool writeOnModelFile=true)
Set Segmentation's area threshold for each class.
SegmentationTestDLL.h
Header file for segmentation module.
SR_MakeSegTestResult
SegTestResult SR_MakeSegTestResult()
Construct a SegTestResult.
SR_SetSegTestForwardTimeLimitVariables
eErrorType SR_SetSegTestForwardTimeLimitVariables(SegTestHandle handle, float forwardTimeLimit, bool bIsToUseForwardTimeLimit, bool writeOnModelFile=true)
Set the Forward time limit variables.
SR_ApplySupResTestFrom8bitCharColorArray
eErrorType SR_ApplySupResTestFrom8bitCharColorArray(SupResTestHandle handle, const unsigned char *imageData, const int height, const int width, SupResTestResult result)
SupResTestHandle 을 이용하여 초해상화를 수행합니다.
SR_MULTI_CLASS_CV_CONTOUR_OUTPUT
@ SR_MULTI_CLASS_CV_CONTOUR_OUTPUT
Definition: SegmentationTestDLL.h:64
SR_GetSupResTestResultImage
eErrorType SR_GetSupResTestResultImage(SupResTestResult superResolutionResult, unsigned char *resultImage)
Get a result image of super resolution.
SR_MULTI_CLASS_MATRIX_OUTPUT
@ SR_MULTI_CLASS_MATRIX_OUTPUT
Definition: SegmentationTestDLL.h:62
SR_GetSegTestInspectionTime
eErrorType SR_GetSegTestInspectionTime(SegTestResult segTestResult, long *inspectionTimeInLong)
Get the inspection time.
SupResTestResult
void * SupResTestResult
Super resolution results handler.
Definition: SuperResolutionTestDLL.h:58
SR_ONE_CLASS_CV_CONTOUR_OUTPUT
@ SR_ONE_CLASS_CV_CONTOUR_OUTPUT
Definition: SegmentationTestDLL.h:63
SR_ApplySupResTestFromImageFileByWideCharPath
eErrorType SR_ApplySupResTestFromImageFileByWideCharPath(SupResTestHandle handle, const wchar_t *imagePath, SupResTestResult result)
SupResTestHandle 을 이용하여 초해상화를 수행합니다.
SR_GetSegTestOneClassNameWithMultiByteCharByIdxWithoutBG
eErrorType SR_GetSegTestOneClassNameWithMultiByteCharByIdxWithoutBG(SegTestHandle handle, const int classIdx, char *className)
Get a multi byte char name of certain class by given index.
GetImageDataByInputImageType
void * GetImageDataByInputImageType(const std::wstring imagePath, const eSRInputImageType inputType, int &height, int &width, int *channel=nullptr)
Get image data from a file path and image size by an allocated pointer for example projects.
Definition: SRUtils.h:138
SR_GetSegTestDeletedObjects
eErrorType SR_GetSegTestDeletedObjects(SegTestResult segTestResult, SR_SegmentedObject *deletedObjects)
Get deleted SR_SegmentedObject s by filter process Segmentation's area threshold.
SR_GetSegTestNumberOfSegmentedObjects
eErrorType SR_GetSegTestNumberOfSegmentedObjects(SegTestResult segTestResult, int *numberOfSegmentedObjects)
Get the number of SR_SegmentedObject.
SR_SetROIInfoFromSeg
eErrorType SR_SetROIInfoFromSeg(SupResTestHandle handle, SegTestHandleForSupRes srcHandle)
SegTestHandleForSupRes 로부터 ROI 정보를 받아 SupResTestHandle에 설정합니다.
SR_DeleteSupResTestResult
eErrorType SR_DeleteSupResTestResult(SupResTestResult result)
Destruct a SupResTestResult.
SR_ONE_CLASS_MATRIX_OUTPUT
@ SR_ONE_CLASS_MATRIX_OUTPUT
Definition: SegmentationTestDLL.h:61
SR_LoadSegTestNetworkInGPU
eErrorType SR_LoadSegTestNetworkInGPU(SegTestHandle handle, int GPUNumber, int batchSize=1)
Allocate required cpu & gpu memory.
SR_SetSegTestIsToStoreCroppedImage
eErrorType SR_SetSegTestIsToStoreCroppedImage(SegTestHandle handle, bool isToStoreCroppedImage, int defaultCropSize, eModeOfCropLargeObjects modeOfCropLargeObjects=SR_CROP_BY_OBJECTSIZE_N_RESIZE_TO_CROPSIZE, float margin=0.05, bool writeOnModelFile=true)
Set the parameters of Segmentation's crop object.
SR_GetSegTestResultOriginalImageSize
eErrorType SR_GetSegTestResultOriginalImageSize(SegTestResult segTestResult, int *width, int *height)
Get the size of inspected image.
eSRInputImageType
eSRInputImageType
Data Type of input Image for example projects.
Definition: SRUtils.h:23
SR_GetSegTestMinScoreThresholdWithoutBG
eErrorType SR_GetSegTestMinScoreThresholdWithoutBG(SegTestHandle handle, int *scoreThreshold)
Get Segmentation's score threshold for each class.
SuperResolutionTestDLL.h
Header file for super resolution module.
SR_CreateSegTestHandleByWideCharPath
SegTestHandle SR_CreateSegTestHandleByWideCharPath(const wchar_t *filePath)
Create a SegTestHandle via wide char path.
SR_ApplySupResTestFromImageFile
eErrorType SR_ApplySupResTestFromImageFile(SupResTestHandle handle, const char *imagePath, SupResTestResult result)
SupResTestHandle 을 이용하여 초해상화를 수행합니다.
UNKNOWN_ERROR
@ UNKNOWN_ERROR
Definition: CommonHeaderDLL.h:44
SR_PIXELSIZE_FILTER_MODE_ON_EXACT
@ SR_PIXELSIZE_FILTER_MODE_ON_EXACT
Definition: CommonHeaderDLL.h:91
SR_DestroySupResTestHandle
eErrorType SR_DestroySupResTestHandle(SupResTestHandle handle)
SupResTestHandle 을 소멸합니다.
SR_DeleteSegTestResult
eErrorType SR_DeleteSegTestResult(SegTestResult segTestResult)
Destruct a SegTestResult.
SR_SetSegTestIsToCalcAverageColor
eErrorType SR_SetSegTestIsToCalcAverageColor(SegTestHandle handle, bool isToCalcAverageColors, bool writeOnModelFile=true)
Set the boolean indicating whether calculate SR_SegmentedObject::averageColor or not.
SR_GetSegTestLoadImageTime
eErrorType SR_GetSegTestLoadImageTime(SegTestResult segTestResult, long *imageLoadingTimeInLong)
Get the image loading time.
convertSRSegmentedObjectToOpencvFormat
void convertSRSegmentedObjectToOpencvFormat(const SR_SegmentedObject &object, std::vector< std::vector< cv::Point >> &contours, std::vector< cv::Vec4i > &hierarchies)
convert SR_SegmentedObject to opencv contours and hierarchies for example projects.
Definition: SRUtils.h:334
SR_GetSegTestOneClassColorByIdxWithoutBG
eErrorType SR_GetSegTestOneClassColorByIdxWithoutBG(SegTestHandle handle, const int classIdx, int *classColor)
Get a color of certain class by given index.
SR_GetSegTestNumberOfDeletedObjects
eErrorType SR_GetSegTestNumberOfDeletedObjects(SegTestResult segTestResult, int *numberOfDeletedObjects)
Get the number of deleted SR_SegmentedObject s by filter process Segmentation's area threshold.
SR_DestroySegTestHandle
eErrorType SR_DestroySegTestHandle(SegTestHandle handle)
Destruct a SegTestHandle.
SR_SetSegTestMinScoreThresholdWithoutBG
eErrorType SR_SetSegTestMinScoreThresholdWithoutBG(SegTestHandle handle, int numOfClasses, int *scoreThreshold, bool writeOnModelFile=true)
Set Segmentation's score threshold for each class.
SR_GetSupResTestInferenceTime
eErrorType SR_GetSupResTestInferenceTime(SupResTestResult superResolutionResult, long *inferenceTimeInLong)
Get the inference time.
SR_SetSegTestIsToCalcObjectScores
eErrorType SR_SetSegTestIsToCalcObjectScores(SegTestHandle handle, bool isToCalcObjectScores, bool writeOnModelFile=true)
Set the boolean indicating whether calculate SR_SegmentedObject::scores or not.
eErrorType
eErrorType
Enumerator indicating error codes.
Definition: CommonHeaderDLL.h:25
SR_PIXELSIZE_FILTER_MODE_OFF
@ SR_PIXELSIZE_FILTER_MODE_OFF
Definition: CommonHeaderDLL.h:89
SegTestHandle
void * SegTestHandle
Segmentation file handler.
Definition: SegmentationTestDLL.h:90
SR_CreateSupResTestHandleByWideCharPath
SupResTestHandle SR_CreateSupResTestHandleByWideCharPath(const wchar_t *filePath)
SupResTestHandle 을 생성합니다.
DisplayFailedImageOnCVWindow
void DisplayFailedImageOnCVWindow(std::wstring &imagePath, std::string failPhrase, std::string windowName, int displayTime, const float resizeFactor)
Display failed image on opencv window for example projects.
Definition: SRUtils.h:273
SRUtils.h
Header file of util functions for example projects.
SR_PIXELSIZE_FILTER_MODE_ON_FAST
@ SR_PIXELSIZE_FILTER_MODE_ON_FAST
Definition: CommonHeaderDLL.h:90
SegTestResult
void * SegTestResult
Segmentation inspection results handler.
Definition: SegmentationTestDLL.h:105
SR_PrintSegTestParametersWithoutBG
eErrorType SR_PrintSegTestParametersWithoutBG(SegTestHandle handle)
Print a model parameters (Segmentation's class information, inspection options...)
SR_GetSegTestOutputMatrixSizeInfo
eErrorType SR_GetSegTestOutputMatrixSizeInfo(SegTestResult segTestResult, int *scoreMatrixChannel, int *scoreMatrixSize)
Get the size of Score matrix.
SupResTestHandle
void * SupResTestHandle
Super resolution handler.
Definition: SuperResolutionTestDLL.h:44
SR_MakeSupResTestResult
SupResTestResult SR_MakeSupResTestResult()
SupResTestResult 를 생성합니다.
SR_ApplySegTestFrom8bitCharGrayArray
eErrorType SR_ApplySegTestFrom8bitCharGrayArray(SegTestHandle handle, const unsigned char *imageData, const int height, const int width, SegTestResult segTestResult, int flag)
Apply segmentation algorithm to 1-channel image by 8-bit data.
SR_GetSupResTestResultImageSize
eErrorType SR_GetSupResTestResultImageSize(SupResTestResult superResolutionResult, int *height, int *width)
Get a size of result image of super resolution.
SR_GetSegTestOutputMatrix
eErrorType SR_GetSegTestOutputMatrix(SegTestResult segTestResult, int scoreMatrixSize, unsigned char *scoreMatrixData)
Get Score matrix.
SR_GetSupResTestLoadImageTime
eErrorType SR_GetSupResTestLoadImageTime(SupResTestResult superResolutionResult, long *imageLoadingTimeInLong)
Get the image loading time.
SR_CROP_BY_OBJECTSIZE_N_RESIZE_TO_CROPSIZE
@ SR_CROP_BY_OBJECTSIZE_N_RESIZE_TO_CROPSIZE
Definition: CommonHeaderDLL.h:100
SR_GetSegTestMaxStrLenOfClassName
eErrorType SR_GetSegTestMaxStrLenOfClassName(SegTestHandle handle, int *len)
Get a maximum length of class name.
SR_LoadSupResTestNetworkInGPU
eErrorType SR_LoadSupResTestNetworkInGPU(SupResTestHandle handle, int gpuIndexNvml, int batchSize=1)
GPU에 네트워크를 위한 메모리를 할당하고 로드합니다.
SR_SetSegTestIsToUseForwardTimeLimit
eErrorType SR_SetSegTestIsToUseForwardTimeLimit(SegTestHandle handle, bool bIsToUseForwardTimeLimit, bool writeOnModelFile=true)
Set the boolean whether the current model is using time limit or not.
NO_ERROR_OUT
@ NO_ERROR_OUT
Definition: CommonHeaderDLL.h:26
SR_GetSegTestMinPixelSizeThresholdWithoutBG
eErrorType SR_GetSegTestMinPixelSizeThresholdWithoutBG(SegTestHandle handle, int *areaThreshold)
Get Segmentation's area threshold for each class.
SR_GetSegTestNumberOfClassesWithoutBG
eErrorType SR_GetSegTestNumberOfClassesWithoutBG(SegTestHandle handle, int *numberOfClasses)
Get the number of classes.
SR_GetSegTestSegmentedObjects
eErrorType SR_GetSegTestSegmentedObjects(SegTestResult segTestResult, SR_SegmentedObject *segmentedObjects)
Get SR_SegmentedObject s.
SR_ApplySupResTestFrom8bitCharGrayArray
eErrorType SR_ApplySupResTestFrom8bitCharGrayArray(SupResTestHandle handle, const unsigned char *imageData, const int height, const int width, SupResTestResult result)
SupResTestHandle 을 이용하여 초해상화를 수행합니다.
SR_GetSegTestOneClassNameWithWideCharByIdxWithoutBG
eErrorType SR_GetSegTestOneClassNameWithWideCharByIdxWithoutBG(SegTestHandle handle, const int classIdx, wchar_t *className)
Get a wide char name of certain class by given index.