C++ Vector Subscript out of range with opencv error

206 Views Asked by At

Any thoughts where I might be going wrong. PS: New to coding and StackOverFlow.



#include<iostream>
#include<opencv2/opencv.hpp>
#include<opencv2/highgui.hpp>
#include<opencv2/imgcodecs.hpp>
#include<opencv2/imgproc.hpp>

//Declare the image variables
cv::Mat img, imgGray, imgBlur, imgCanny, imgDil;

void GetContours(cv::Mat dilatedImg, cv::Mat originalImg);

int main(int argc, char** argv)
{
   std::string path="E://Trial//Resources//Resources//shapes.png";
   img= cv::imread(path);
 

   //pre=processing
   cv::cvtColor(img,imgGray,cv::COLOR_BGR2GRAY);
   cv::GaussianBlur(imgGray, imgBlur,cv::Size(3,3),3,0);
   cv::Canny(imgBlur,imgCanny,25,75);
   cv::Mat kernel= cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3,3)) ;
   cv::dilate(imgCanny,imgDil,kernel);

   //Processing
   GetContours(imgDil, img);
   
   //Display contours
   cv::imshow("Image",img);
   cv::waitKey(0);

   return 0;
}

void GetContours(cv::Mat dilatedImg, cv::Mat originalImg)
{
   std::vector<std::vector<cv::Point>> contours;
   std::vector<cv::Vec4i> hierarchy;
   std::vector<std::vector<cv::Point>> conPoly(contours.size());
   double area=0;


   //finds the contours in the shapes
   cv::findContours(dilatedImg, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
   
   for(int i=0; i<contours.size(); i++)
   {
      area = cv::contourArea(contours[i]);
      std::cout<<area<<std::endl;
      
      if(area>1000)
      {
         //Draw contours around shapes
         cv::drawContours(originalImg,contours, i,cv::Scalar(255,0,255),2);
         
         // create a bounding box around the shapes
         cv::approxPolyDP(cv::Mat(contours[i]), conPoly[i], 3, true);
        
         //draw contours using the contour points
         cv::drawContours(originalImg,conPoly, i,cv::Scalar(255,255,0),2);         
      }
   }
}



ApproxPollyDP is where I think the code is failing. I am getting an Assertion Failed error with vector out of range. I think I am doing some silly mistake but I have not been able to debug the issue.

2

There are 2 best solutions below

1
Vlad from Moscow On

The vector conPoly declared as shown below

std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;
std::vector<std::vector<cv::Point>> conPoly(contours.size());

is an empty vector because initially contours.size() is equal tp 0 because the vector contours in turn is declared as empty.

So using the subscript operator with the vector

cv::approxPolyDP(cv::Mat(contours[i]), conPoly[i], 3, true);

invokes undefined behavior.

1
Mind Chants On

So this works:

std::vector<std::vector<cv::Point>> contours;
   std::vector<cv::Vec4i> hierarchy;
   double area=0;


   //finds the contours in the shapes
   cv::findContours(dilatedImg, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
   
   std::vector<std::vector<cv::Point>> conPoly(contours.size());