SaigeVision C/C++ 1.5.0
SaigeVision API document for C/C++
 
Loading...
Searching...
No Matches
ExampleSegRuntimeMultiPage.cpp

This is an example of how to inspect sample multi page images of 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 filter contours by region.*/
//#define SR_FILTER_OBJECTS_BY_REGION
/* 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 exclude matrix output with CV_CONTOUR flag to reduce inspecting time.*/
//#define SR_MATRIX_OUTPUT_WITH_CV_CONTOUR_FLAG
/* define this variable when user want to limit the forward time of classfication algorithm. */
//#define SR_USE_FORWARD_TIME_LIMIT
int main()
{
// 검사할 페이지 수 the number of pages
int numberOfPages = 2; // 설정 필요
// trained model path
std::wstring trainedModelPath = L"~"; // 설정 필요
// image paths to classify
// the number of images to inspect x the number of pages
std::vector<std::vector<std::wstring>> imagePaths; // 설정 필요
/***********************************************************
* 0. 이미지 인풋 타입 설정
* inputImageType -
* UC8bitImage: from memory(8bit unsigned char image)
***********************************************************/
eSRInputImageType inputImageType = eSRInputImageType::UC8bitImage;
/***********************************************************
* 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 = 0.5;
/***********************************************************
* 0-2. GPU 번호 설정
* gpuIndex - 사용하고자 하는 gpu의 번호
* Multi GPU 가 가능한 License의 경우에 한하여 gpuIndex를
* 0~3까지 설정해 줄 수 있다. 아닌 경우 gpuIndex는 0을 사용하여야 한다.
***********************************************************/
int gpuIndex = 0;
/***********************************************************
* 0-3. Segmentation 검사 방법 설정
***********************************************************/
/***********************************************************
* 1. 모델 파일 및 검사 결과 handle 생성,
* Create handles for model files and inspection results
***********************************************************/
SegTestHandle handle = nullptr;
srStatus = SR_CreateSegTestHandleByWideCharPath_ErrorType(&handle, trainedModelPath.c_str());
if (srStatus != NO_ERROR_OUT || handle == nullptr)
{
std::wcout << "Saige Vision failed: Please check the file path of trained model." << std::endl;
}
SegTestResult segTestResult = nullptr;
srStatus = SR_MakeSegTestResult_ErrorType(&segTestResult);
if (srStatus != NO_ERROR_OUT)
{
PrintErrorType(srStatus, verbosity);
return -1;
}
/***********************************************************
* 2. 클래스 정보 확인 (Optional)
* Check class information
***********************************************************/
// Print segmentation Test Parameters() by calling one fuctions
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(handle, &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(handle, &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(handle, 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(handle, 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(handle, 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 the number and name of pages
***********************************************************/
// page information
int numberOfPagesInFile = 0;
int maxStrLenOfPageName = 0;
char* pageNameOutput = nullptr;
srStatus = SR_GetSegTestNumberOfPages(handle, &numberOfPagesInFile);
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;
}
// "The number of pages mismatches"
assert(numberOfPagesInFile == numberOfPages);
srStatus = SR_GetSegTestMaxStrLenOfPageName(handle, &maxStrLenOfPageName);
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;
}
pageNameOutput = new char[maxStrLenOfPageName];
for (int i = 0; i < numberOfPagesInFile; i++)
{
srStatus = SR_GetSegTestOnePageNameWithMultiByteChar(handle, i, pageNameOutput);
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 pages) or input pointer is not allocated (nullptr).
return -1;
}
printf(" - %d-th page name: %s\n", i, pageNameOutput);
}
delete[] pageNameOutput;
/***********************************************************
* 4. 검사 옵션 확인 및 수정 (Optional)
* Check inspection options and set new values
***********************************************************/
std::vector<int> scoreThresholdOutput(numberOfClassesOutput);
std::vector<int> pixelSizeThresholdOutput(numberOfClassesOutput);
// Get the score threshold for each class
srStatus = SR_GetSegTestMinScoreThresholdWithoutBG(handle, 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(handle, 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] = 0; // 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_FILTER_OBJECTS_BY_REGION
// filter object 를 적용할 region 설정 시 아래의 함수 (SR_SetSegFilterObjByRegion, SR_SetSegFilterObjSimpleParameters)를 사용하기 보다
// SAIGE VISION Developer (UI)의 Analyze/Inspect 에서 설정하는 것을 권장합니다.
srStatus = SR_SetSegFilterObjByRegion(handle, eFilterObjByRegionType::SR_SIMPLE, true);
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;
}
std::vector<float> filterObjSimpleParams(4);
filterObjSimpleParams[0] = 0.1f; // left, in [0, 1]
filterObjSimpleParams[1] = 0.1f; // top, in [0, 1]
filterObjSimpleParams[2] = 0.8f; // width, in [0, 1], left + width in [0, 1]
filterObjSimpleParams[3] = 0.8f; // height, in [0, 1], top + height in [0, 1]
srStatus = SR_SetSegFilterObjSimpleParameters(handle, filterObjSimpleParams.data(), true);
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_MATRIX_OUTPUT_WITH_CV_CONTOUR_FLAG
srStatus = SR_SetSegTestIsMatrixOutputIncluded(handle, 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
#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(handle, 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
/***********************************************************
* 5. 메모리를 GPU 및 CPU에 할당합니다.
* Allocate GPU and CPU memory
***********************************************************/
srStatus = SR_LoadSegTestNetworkInGPU(handle, 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;
}
for (size_t i_img = 0; i_img < imagePaths.size(); i_img++)
{
int height = 0, width = 0;
std::vector<int> channels(numberOfPages);
unsigned char** ucImageData = new unsigned char*[numberOfPages]; // arrays of unsigned char image data
for (size_t i_page = 0; i_page < numberOfPages; i_page++)
{
int h, w;
ucImageData[i_page] = (unsigned char*)GetImageDataByInputImageType(imagePaths[i_img][i_page], inputImageType, h, w, &(channels[i_page]));
if (i_page != 0) {
// "width and height of all the images should be the same"
assert(h == height && w == width);
}
height = h;
width = w;
}
/***********************************************************
* 6. 이미지 검사하기, Inspect images
***********************************************************/
eErrorType errorType = NO_ERROR_OUT;
if (inputImageType == eSRInputImageType::UC8bitImage)
{
errorType = SR_ApplySegTestFromMultiPage8bitCharArrays(handle, numberOfPages, ucImageData, height, width, channels.data(), 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][0], "FAIL TO segment", "segmentation Result", displayTime, resizeFactor);
}
continue; // jump to next image
}
/***********************************************************
* 7. 검사 결과 받아오기, Retrieve inspection results
***********************************************************/
if (verbosity >= 2)
{
long inspectionTimeOutput = 0, loadImageTimeOutput = 0;
// Get the inspection time
srStatus = SR_GetSegTestInspectionTime(segTestResult, &inspectionTimeOutput);
if (srStatus != NO_ERROR_OUT)
{
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
PrintErrorType(srStatus, verbosity);
}
// Get the image-loading time
srStatus = SR_GetSegTestLoadImageTime(segTestResult, &loadImageTimeOutput);
if (srStatus != NO_ERROR_OUT)
{
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
PrintErrorType(srStatus, verbosity);
}
// Get if the size of inspected image exceeded max inspection size
bool isExceededMaxInspectionSize = false;
srStatus = SR_GetSegTestIsExceededMaxInspectionSize(segTestResult, &isExceededMaxInspectionSize);
if (srStatus != NO_ERROR_OUT)
{
// if you get this error, it's possible that the input pointer is not allocated (nullptr).
PrintErrorType(srStatus, verbosity);
}
// Get if image is cropped due to lack of GPU memory
bool isImageCropped = false;
srStatus = SR_GetSegTestIsImageCropped(segTestResult, &isImageCropped);
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
}
std::cout << "====== Segmentation Test Result (Total) ======" << std::endl;
std::cout << " - Total Image Loading time: " << loadImageTimeOutput << std::endl;
std::cout << " - Total Inspection time: " << inspectionTimeOutput << std::endl;
std::cout << " - Is exceeded max inspection size: " << isExceededMaxInspectionSize << std::endl;
std::cout << " - Is image cropped: " << isImageCropped << std::endl << std::endl;
}
/* 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;
for (size_t i_p = 0; i_p < numberOfPages; i_p++)
{
std::wcout << imagePaths[i_img][i_p] << std::endl;
}
std::cout << " - Image width, height: " << width << ", " << height << 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 (verbosity >= 2)
{
std::cout << " - the number of segmented objects: " << segmentedObject.size() << std::endl;
for (int i = 0; i < segmentedObject.size(); i++)
{
std::cout << " - " << i << "-th segmented objects : " <<
"class[" << segmentedObject[i].classIdx << "], " <<
"area[" << segmentedObject[i].area << "], " <<
"width[" << segmentedObject[i].width << "], " <<
"height[" << segmentedObject[i].height << "], " <<
"x_center[" << segmentedObject[i].xCenter << "], " <<
"y_center[" << segmentedObject[i].yCenter << "], " <<
"scores(average, min, max)[" << segmentedObject[i].scores[0] << ", "
<< segmentedObject[i].scores[1] << ", "
<< segmentedObject[i].scores[2] << "], "
"average_color(B, G, R)[" << segmentedObject[i].averageColor[0] << ", " <<
segmentedObject[i].averageColor[1] << ", " <<
segmentedObject[i].averageColor[2] << "]" << std::endl;
}
}
// 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(height, width, CV_MAKETYPE(CV_8U, channels[0]), ucImageData[0]);
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", width * resizeFactor, height * 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 < width * height; i_pixel++)
{
int maxVal = 0;
int channel = 0;
for (int c = 0; c < numberOfClassesOutput; c++)
{
if (outputMatrix[i_pixel + c * width * height] > maxVal)
{
maxVal = outputMatrix[i_pixel + c * width * height];
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", width * resizeFactor, height * 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);
}
}
#endif
}
}
for (size_t i_p = 0; i_p < numberOfPages; i_p++)
{
if (ucImageData[i_p] != nullptr)
{
delete[] ucImageData[i_p];
ucImageData[i_p] = nullptr;
}
}
if (ucImageData != nullptr)
{
delete[] ucImageData;
ucImageData = nullptr;
}
}
/***********************************************************
* 8. Handle 파괴, Destruct handles
***********************************************************/
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(handle);
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;
}
eErrorType
Enumerator indicating error codes.
Definition: CommonHeaderDLL.h:30
@ NO_ERROR_OUT
Definition: CommonHeaderDLL.h:31
@ SR_PIXELSIZE_FILTER_MODE_ON_FAST
Definition: CommonHeaderDLL.h:97
@ SR_PIXELSIZE_FILTER_MODE_ON_EXACT
Definition: CommonHeaderDLL.h:98
@ SR_PIXELSIZE_FILTER_MODE_OFF
Definition: CommonHeaderDLL.h:96
@ SR_CROP_BY_OBJECTSIZE_N_RESIZE_TO_CROPSIZE
Definition: CommonHeaderDLL.h:107
Header file of util functions for example projects.
eSRInputImageType
Data Type of input Image for example projects.
Definition: SRUtils.h:23
Header file for segmentation module.
eErrorType SR_PrintSegTestParametersWithoutBG(SegTestHandle handle)
Print a model parameters (Segmentation's class information, inspection options...)
@ SR_ONE_CLASS_CV_CONTOUR_OUTPUT
Definition: SegmentationTestDLL.h:63
@ SR_MULTI_CLASS_CV_CONTOUR_OUTPUT
Definition: SegmentationTestDLL.h:64
@ SR_ONE_CLASS_MATRIX_OUTPUT
Definition: SegmentationTestDLL.h:61
@ SR_MULTI_CLASS_MATRIX_OUTPUT
Definition: SegmentationTestDLL.h:62
eErrorType SR_LoadSegTestNetworkInGPU(SegTestHandle handle, int GPUNumber, int batchSize=1)
Allocate required cpu & gpu memory.
eErrorType SR_SetSegTestMinPixelSizeThresholdWithoutBG(SegTestHandle handle, int numOfClasses, int *areaThreshold, bool writeOnModelFile=true)
Set Segmentation's area threshold for each class.
eErrorType SR_GetSegTestMinPixelSizeThresholdWithoutBG(SegTestHandle handle, int *areaThreshold)
Get Segmentation's area threshold for each class.
eErrorType SR_SetSegTestModeOfFilteringByPixelSize(SegTestHandle handle, eModeOfPixelSizeFilter modeOfFiltering, bool writeOnModelFile=true)
Set the mode of filtering by Segmentation's area threshold.
eErrorType SR_GetSegTestOneClassNameWithWideCharByIdxWithoutBG(SegTestHandle handle, const int classIdx, wchar_t *className)
Get a wide char name of certain class by given index.
eErrorType SR_GetSegTestMaxStrLenOfClassName(SegTestHandle handle, int *len)
Get a maximum length of class name.
eErrorType SR_GetSegTestNumberOfClassesWithoutBG(SegTestHandle handle, int *numberOfClasses)
Get the number of classes.
eErrorType SR_GetSegTestOneClassNameWithMultiByteCharByIdxWithoutBG(SegTestHandle handle, const int classIdx, char *className)
Get a multi byte char name of certain class by given index.
eErrorType SR_GetSegTestOneClassColorByIdxWithoutBG(SegTestHandle handle, const int classIdx, int *classColor)
Get a color of certain class by given index.
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.
eErrorType SR_SetSegFilterObjSimpleParameters(SegTestHandle handle, float *simpleParams, bool writeOnModelFile=true)
Set the simple parameters of filtering object by Segmentation's filter object by region.
eErrorType SR_SetSegFilterObjByRegion(SegTestHandle handle, eFilterObjByRegionType filterObjType, bool writeOnModelFile=true)
Set the filtering object type by Segmentation's filter object by region.
eErrorType SR_SetSegTestForwardTimeLimitVariables(SegTestHandle handle, float forwardTimeLimit, bool bIsToUseForwardTimeLimit, bool writeOnModelFile=true)
Set the Forward time limit variables.
eErrorType SR_SetSegTestIsToUseForwardTimeLimit(SegTestHandle handle, bool bIsToUseForwardTimeLimit, bool writeOnModelFile=true)
Set the boolean whether the current model is using time limit or not.
void * SegTestHandle
Segmentation file handler.
Definition: SegmentationTestDLL.h:90
eErrorType SR_CreateSegTestHandleByWideCharPath_ErrorType(SegTestHandle *segTestHandle, const wchar_t *filePath)
Create a SegTestHandle via wide char path.
void * SegTestResult
Segmentation inspection results handler.
Definition: SegmentationTestDLL.h:105
eErrorType SR_MakeSegTestResult_ErrorType(SegTestResult *segTestResult)
Construct a SegTestResult.
eErrorType SR_DestroySegTestHandle(SegTestHandle handle)
Destruct a SegTestHandle.
eErrorType SR_DeleteSegTestResult(SegTestResult segTestResult)
Destruct a SegTestResult.
eErrorType SR_SetSegTestIsMatrixOutputIncluded(SegTestHandle handle, bool isMatrixOutputIncluded, bool writeOnModelFile=true)
Set the boolean indicating whether include matrix output or not.
eErrorType SR_ApplySegTestFromMultiPage8bitCharArrays(SegTestHandle handle, int numOfPages, unsigned char **imageData, int height, int width, int *channels, SegTestResult segTestResult, int flag)
Apply segmentation algorithm to multi-page image by 8-bit data (multi-page).
eErrorType SR_GetSegTestIsImageCropped(SegTestResult segTestResult, bool *isImageCropped)
Get whether the image is cropped due to lack of GPU memory.
eErrorType SR_GetSegTestDeletedObjects(SegTestResult segTestResult, SR_SegmentedObject *deletedObjects)
Get deleted SR_SegmentedObject s by filter process Segmentation's area threshold.
eErrorType SR_GetSegTestLoadImageTime(SegTestResult segTestResult, long *imageLoadingTimeInLong)
Get the image loading time.
eErrorType SR_GetSegTestNumberOfDeletedObjects(SegTestResult segTestResult, int *numberOfDeletedObjects)
Get the number of deleted SR_SegmentedObject s by filter process Segmentation's area threshold.
eErrorType SR_GetSegTestInspectionTime(SegTestResult segTestResult, long *inspectionTimeInLong)
Get the inspection time.
eErrorType SR_GetSegTestOutputMatrix(SegTestResult segTestResult, int scoreMatrixSize, unsigned char *scoreMatrixData)
Get Score matrix.
eErrorType SR_GetSegTestNumberOfSegmentedObjects(SegTestResult segTestResult, int *numberOfSegmentedObjects)
Get the number of SR_SegmentedObject.
eErrorType SR_GetSegTestIsExceededMaxInspectionSize(SegTestResult segTestResult, bool *isExceededMaxInspectionSize)
Get whether the size of inspected image exceeds max inspection size.
eErrorType SR_GetSegTestSegmentedObjects(SegTestResult segTestResult, SR_SegmentedObject *segmentedObjects)
Get SR_SegmentedObject s.
eErrorType SR_GetSegTestOutputMatrixSizeInfo(SegTestResult segTestResult, int *scoreMatrixChannel, int *scoreMatrixSize)
Get the size of Score matrix.
eErrorType SR_GetSegTestNumberOfPages(SegTestHandle handle, int *numberOfPages)
Get the number of pages.
eErrorType SR_GetSegTestMaxStrLenOfPageName(SegTestHandle handle, int *len)
Get a maximum length of page name.
eErrorType SR_GetSegTestOnePageNameWithMultiByteChar(SegTestHandle handle, const int pageIdx, char *pageName)
Get a multi byte char name of certain page by given index.
eErrorType SR_SetSegTestIsToCalcObjectScores(SegTestHandle handle, bool isToCalcObjectScores, bool writeOnModelFile=true)
Set the boolean indicating whether calculate SR_SegmentedObject::scores or not.
eErrorType SR_GetSegTestMinScoreThresholdWithoutBG(SegTestHandle handle, int *scoreThreshold)
Get Segmentation's score threshold for each class.
eErrorType SR_SetSegTestMinScoreThresholdWithoutBG(SegTestHandle handle, int numOfClasses, int *scoreThreshold, bool writeOnModelFile=true)
Set Segmentation's score threshold for each class.