I am getting a vector subscript out of range exception, and a breakpoint is triggered at line 53. It is saving only 3 images out of all images being processed. How to solve this problem??
#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#include "opencv\cv.h"
#include <vector>
using namespace cv;
using namespace std;
vector<String> files;
int main()
{
int largest_area = 0;
int largest_contour_index = 0;
Rect bounding_rect;
cv::glob("C:/Proj/Folder/5.Morph/Goal Keeping/1. Low balls/*.jpg", files);
for (size_t i = 0; i < files.size(); i++) {
Mat src = imread(files[i]);
Mat thr(src.rows, src.cols, CV_8UC1);
Mat dst(src.rows, src.cols, CV_8UC1, Scalar::all(0));
cvtColor(src, thr, CV_BGR2GRAY); //Convert to gray
threshold(thr, thr, 25, 255, THRESH_BINARY); //Threshold the gray
vector<vector<Point>> contours; // Vector for storing contour
vector<Vec4i> hierarchy;
findContours(thr, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); // Find the contours in the image
for (int j = 0; j< contours.size(); j++) // iterate through each contour.
{
double a = contourArea(contours[j], false); // Find the area of contour
if (a>largest_area) {
largest_area = a;
largest_contour_index = j; //Store the index of largest contour
bounding_rect = boundingRect(contours[j]); // Find the bounding rectangle for biggest contour
}
}
if (!contours.empty()) {
Moments mom = cv::moments(contours[0]);
}
Scalar color(255, 255, 255);
***LINE 53*** drawContours(dst, contours, largest_contour_index, color, CV_FILLED, 8, hierarchy); // Draw the largest contour using previously stored index.
rectangle(src, bounding_rect, Scalar(0, 255, 0), 1, 8, 0);
imshow("src", src);
imshow("Largest Contour", dst);
// display result
std::stringstream files(std::stringstream::in | std::stringstream::out);
files << "Contour" << i << ".jpg";
std::cout << "writing " << files.str().c_str() << " to disk" << std::endl;
imwrite(files.str().c_str(), dst);
}
waitKey(0);
return 0;
}