I am using a function like this;
#include <exception>
Mat large = imread(path+name);
Mat rgb;
if (large.rows > 2500 || large.cols > 1250)
{
pyrDown(large, rgb);
}
else
{
rgb = large.clone();
}
cv::Mat smallx;
cvtColor(rgb, smallx, CV_BGR2GRAY);
Mat grad;
Mat morphKernel = getStructuringElement(MORPH_ELLIPSE, Size(3, 3));
cv::morphologyEx(smallx, grad, MORPH_GRADIENT, morphKernel);
Mat bw;
cv::threshold(document, document, 100, 255, cv::THRESH_BINARY + cv::THRESH_OTSU);
cv::threshold(grad, bw, 100, 255, THRESH_BINARY + THRESH_OTSU);
Mat connected;
morphKernel = getStructuringElement(MORPH_RECT, Size(9, 1));
cv::morphologyEx(bw, connected, MORPH_CLOSE, morphKernel);
Mat mask = Mat::zeros(bw.size(), CV_8UC1);
vector<vector<Point>> contours(50000);
vector<Vec4i> hierarchy(50000);
cv::findContours(connected, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
int counter = 0;
std::string coordinates = "";
for (int idx = 0; idx >= 0; idx = hierarchy[idx][0])
{
Rect rect = boundingRect(contours[idx]);
counter++;
Mat maskROI(mask, rect);
maskROI = Scalar(0, 0, 0);
// fill the contour
drawContours(mask, contours, idx, Scalar(255, 255, 255), CV_FILLED);
// ratio of non-zero pixels in the filled region
double r = (double)countNonZero(maskROI) / (rect.width*rect.height);
if (r > .45 && (rect.height > 8 && rect.width > 8))
{
rectangle(rgb, rect, Scalar(0, 255, 255), 2);
coordinates = coordinates + (std::to_string(counter) + "," + std::to_string(rect.x) + ", " + std::to_string(rect.y) + ", " + std::to_string(rect.width) + ", " + std::to_string(rect.height) + "#");
}
}
return coordinates;
Some input images prompt exception when function returns, it throws me to "_Mybase::deallocate(_Ptr, _Count);"
code block in xmemory0 class. I must catch this kind of errors and prevent this process from unexpected suspensions