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.
The vector
conPolydeclared as shown belowis an empty vector because initially
contours.size()is equal tp0because the vectorcontoursin turn is declared as empty.So using the subscript operator with the vector
invokes undefined behavior.