Opencv cv::Subtract method throwing System.Runtime.InteropServices.SEHException Exception - c++

I am currently trying to implement the Lucy Richardson algorithm in Opencv, when it comes to running the 'cv::subtract' method in my program it throws an InteropServices exception (stack trace below)
************** Exception Text **************
System.Runtime.InteropServices.SEHException (0x80004005): External has thrown an exception.
at cv.Mat.=(Mat* , MatExpr* expr) in e:\opencv\opencv\build\include\opencv2\core\mat.inl.hpp:line 3107
at LucyRichardson.LucyRich(LucyRichardson* , Mat* , basic_string<char\,std::char_traits<char>\,std::allocator<char> >* imagePath) in e:\documents\development\realtimeimageprocessing\imageprocessing\imageprocessing\lucyrichardson.cpp:line 63
Below is the block of code where the error occurs, it is thrown on the second line.
im_correction = cv::Mat (cvSize(383, 357), 8, 1);
cv::subtract(im, im_conv_kernel, im_correction);
cv::namedWindow("Sub");
cv::imshow("Sub", im_correction);
The variables im and im_conv_kernel are both of type cv::Mat and are correctly populated and the variable im_correction I have tried creating a version of before I save the result of the subtraction in.
I am using cv::subtractions fine in other parts of the program.
Does anyone know why this error occurs and how I could fix it? Or if there is a different method I could try for the subtraction?

I have worked out where the problem was I needed to make sure all of the images where of the same type. - After adding the below three lines before performing the subtract it worked fine.
im.convertTo(im, CV_8UC1);
im_conv_kernel.convertTo(im_conv_kernel, CV_8UC1);
im_correction.convertTo(im_correction, CV_8UC1);

Related

Error when using Decision Trees in OpenCV 3.0.0-rc1

I am doing some machine learning in OpenCV and i'm using Decision Trees. I am currently using OpenCV 3.0.0-rc1. Whenever i attempt to train Decision Trees with my training data and labels, i get either
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
or
Segmentation fault
Depending on what i put into setMaxDepth(); if the number is larger than 22, it's bad_alloc, else it's seg fault.
Here's my source code:
//import data
Mat trainData=imread("/home/jetson/Documents/CB/ml/td.jpg",CV_LOAD_IMAGE_GRAYSCALE);
Mat labels=imread("/home/jetson/Documents/CB/ml/lab.jpg",CV_LOAD_IMAGE_GRAYSCALE);
//convert to the right type
trainData.convertTo(trainData,CV_32FC1);
labels.convertTo(labels,CV_32SC1);
transpose(trainData,trainData);
Ptr<ml::TrainData> tData = ml::TrainData::create(trainData, ml::ROW_SAMPLE, labels);
cout <<"Training data ready\n";
Ptr<ml::DTrees> dec_trees = ml::DTrees::create();
//params
dec_trees->setMaxDepth(1);
dec_trees->setMinSampleCount(10);
dec_trees->setRegressionAccuracy(0.01f);
dec_trees->setUseSurrogates(false);
dec_trees->setMaxCategories(2);
dec_trees->setCVFolds(10);
dec_trees->setUse1SERule(true);
dec_trees->setTruncatePrunedTree(true);
dec_trees->setPriors(Mat());
cout <<"Params set\n";
dec_trees->train(tData);
cout <<"Done!\n";`
In addition to this, when i try to train a SVM model with the same data, using the same steps (below) it works just fine.
Ptr<ml::SVM> svm = ml::SVM::create();
//params
svm->setType(ml::SVM::C_SVC);
svm->setKernel(ml::SVM::POLY);
svm->setGamma(3);
svm->setDegree(0.1);
cout <<"Params set\n";
svm->train(tData);
cout <<"Done!\n";
I need to point out that the error occurs when i try to train the model. I'm using the default parameters for decision trees, as suggested on the OpenCV documentation page.
Does anybody know what's wrong here and how to go about fixing my problem?
Thanks in advance.
EDIT: I upgraded OpenCV to version 3.0.0 and the issues stay the same

C++ exception in cv::BFMatcher

I am having problems with the cv::BFMatcher when I try to perform the feature matching. I compute the descriptors with the xfeatures2D::SIFT descriptor. When I try to perform the matching the application output shows "Exception at 0x7ff833308b9c, code: 0xe06d7363: C++ exception, flags=0x1 (execution cannot be continued) (first chance) at f:\dd\vctools\crt_bld\self_64_amd64\crt\src\xthrow.cpp:13"
The code is something like:
matchesltor.clear();
matchesrtol.clear();
cv::BFMatcher matcher(cv::NORM_L2);
ProcessedImageData *imageDataLeft = mImageDataMap.value(mapKeyList.at(m));
std::vector<cv::KeyPoint> tiePointsLeft = imageDataLeft->getTiepoints();
cv::Mat descriptorsLeft= imageDataLeft->getDescriptors();
ProcessedImageData *imageDataRight = mImageDataMap.value(mapKeyList.at(n));
std::vector<cv::KeyPoint> tiePointsRight = imageDataRight->getTiepoints();
cv::Mat descriptorsRight= imageDataRight->getDescriptors();
matcher.knnMatch(descriptorsLeft,descriptorsRight,matchesltor,2)
matcher.knnMatch(descriptorsRight,descriptorsLeft,matchesrtol,2)
The output message is shown in the firts line that performs the matching "matcher.knnMatch(descriptorsLeft,descriptorsRight,matchesltor,2)".
The strange thing is that it work in a single qt project that only perform the tie point detection, tie point description and matching but when I try to join it in other project (same code, same compiler and same qt version) it shows that output message and the execution stop (the application does not break).
Thanks for your help.

why this code is crashing on cvtColor?

I have this code:
void * imageBuffer = reinterpret_cast<void *>(exposureBuffer + imageHeader->imgoffset);
cv::Mat imageRaw(imageHeader->height, imageHeader->width, CV_8UC1, imageBuffer);
cv::Mat imageColour;
cv::cvtColor(imageRaw, imageColour, cv::COLOR_BayerGR2BGR);
when I run this and stops debugger on this line:
cv::Mat imageColour;
I can see that imageRaw has a valid image in it (I can see the image in image view and it is a valid image.)
but then the application crashes on this line:
cv::cvtColor(imageRaw, imageColour, cv::COLOR_BayerGR2BGR);
and it seems that a mat file was created but not enough memory allocated for it.
The error message is:
Unhandled exception at 0x00007FF7503F992B in test_PictureProcessing.exe: 0xC0000005: Access violation reading location 0x0000000000000023.
I am using OpenCv 3. I have similar code which runs successfully on openCV 2.
Edit1
I changed the code to this one to make sure that imagebuffer is a valid buffer and the fact that I am not initializing imageColour is not the problem:
void *imageBuffer = new char[imageHeader->height* imageHeader->width];
cv::Mat imageRaw(imageHeader->height, imageHeader->width, CV_8UC1, imageBuffer);
cv::Mat imageColour = imageRaw.clone();
but I am still getting error on this line:
cv::Mat imageColour = imageRaw.clone();
Edit 2
This is also crashing!
cv::Mat imageRaw(imageHeader->height, imageHeader->width, CV_8UC1);
cv::Mat imageColour = imageRaw.clone();
Why this simple code crashing?
I found the problem which is very strange!
I forgot to include opencv.hpp to my source file after adding it, it worked perfectly.
It is strange as I did not get any compile error, but I got run time error.
If you see your openCV behave strangely, make sure that you included opencv.hpp to your source code. it may help you to solve your problem! Not all problems are coming from missing this header as CroCo mentioned.

error retrieving background image from BackgroundSubtractorMOG2

I'm trying to get the background image from BackgroundSubtractorMOG2:
bg->getBackgroundImage(back);
but I get a Thread 1 SIGABRT (which as a c++ n00b puzzles me)
and this error:
OpenCV Error: Assertion failed (nchannels == 3) in getBackgroundImage, file /Users/hm/Downloads/OpenCV-2.4.4/modules/video/src/bgfg_gaussmix2.cpp, line 579
libc++abi.dylib: terminate called throwing an exception
(lldb)
I'm not sure what the problem is, suspecting it's something to do with the nmixtures paramater, but I've left that as the default(3). Any hints ?
It looks like you need to use 3 channel images rather than grayscale. Make sure the image type you are using is CV_8UC3 or if you are reading from a file use cv::imread('path/to/file') with no additional arguments.

Application crashes on equalizeHist of OpenCV

My MFC app runs various API from OpenCV2. Everything else is working fine. But when my program runs
cv::Mat result;
cv::equalizeHist(m_cvImage,result);
I get following runtime exception.
Unhandled exception at 0x7727fbae in OpenCVTest.exe: Microsoft C++ exception: cv::Exception at memory location 0x0029e944..
"C:\slave\WinInstallerMegaPack\src\opencv\modules\imgproc\src\histogram.cpp:2430: error: (-215) CV_ARE_SIZES_EQ(src, dst) && CV_ARE_TYPES_EQ(src, dst) && CV_MAT_TYPE(src->type) == CV_8UC1"
According to debugger, the exception was thrown in the middle of processing (about 40%) the image in equalizeHist. Is there anything I need to do? FYI: I am using binary OpenCV provided by its web site.
UPDATE:
I've resolved this issue by converting images to gray-level before equalizing it. I just didn't know
the function only works with gray-level image
images that look like gray-level can be non-gray.
I imagine the problem you are encountering is that m_cvImage is a 3-channel image. So, you need to convert it to a grayscale image before you can call equalizeHist.
cvtColor(m_cvImage, m_cvImage, CV_BGR2GRAY);
cv::Mat result;
cv::equalizeHist(m_cvImage, result);
Also, have a look at the EqualizeHist_Demo.cpp tutorial sample to see how it is used.