I am trying to draw a bounding box around contours using OpenCV. This is a real time application where all the images are grabbed from a camera real time, and Following is the important part of the code
RTMotionDetector.h
vector<vector<Point>> *contours;
vector<vector<Point>> *contoursPoly;
RTMotionDetector.cpp
RTMotionDetector::RTMotionDetector(void)
{
current = new Mat();
currentGrey = new Mat();
canny = new Mat();
next = new Mat();
absolute = new Mat();
cam1 = new VideoCapture();
cam2 = new VideoCapture();
contours = new vector<vector<Point>>();
contoursPoly = new vector<vector<Point>>();
boundRect = new vector<Rect>();
}
double RTMotionDetector::getMSE(Mat I1, Mat I2)
{
Mat s1;
//Find difference
cv::absdiff(I1, I2, s1); // |I1 - I2|
imshow("Difference",s1);
//Do canny to get edges
cv::Canny(s1,*canny,30,30,3);
imshow("Canny",*canny);
//Find contours
findContours(*canny,*contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);
//System::Windows::Forms::MessageBox::Show(""+contours->size());
//Draw contours
drawContours(*current,*contours,-1,Scalar(0,0,255),2);
for(int i=0;i<contours->size();i++)
{
cv::approxPolyDP(Mat((*contours)[i]),(*contoursPoly)[i],3,true);
//boundRect[i] = boundingRect(contoursPoly[i]);
}
}
As soon as the following part gets executed, I am getting an error
cv::approxPolyDP(Mat((*contours)[i]),(*contoursPoly)[i],3,true);
Here is the error I am getting.
If I comment out that piece of code, then no issues. I know this is ArrayIndexOutOfBounds
issue but I really can't find a fix. May be because I am new to Windows Programming.
It is very important that contours
stay as a pointer instead of local variable, because local variable slowed the program in an unbelievable way.
You need to find which access to which vector has gone beyond its bounds.
You loop til the size of contours,
for(int i=0;i<contours->size();i++)
but then access (*contoursPoly)[i]
I would hazard a guess that the contoursPoly has gone beyond its bounds, which you can check by breaking into the debugger as suggested.
Changing the loop to
for(int i=0;i<contours->size() && i<contoursPoly->size();i++)
might solve the immediate problem.