当我运行以下代码时,我将此异常向量下标超出范围,此代码在图像上成功运行,但是当我更改图像时发生异常。
Mat bw;
inRange(output1, Scalar(low_h, low_s, low_v), Scalar(high_h, high_s, high_v), bw);
vector<vector<Point> > contours;
findContours(bw.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
Mat dst = Mat::zeros(input_image.size(), input_image.type());
for(unsigned int i=0;i<contours.size();i++)
{
cout << "# of contour points: " << contours[i].size() << endl ;
for(unsigned int j=0;j<contours[i].size();j++)
{
cout << "Point(x,y)=" << contours[i][j]<< endl;
}
cout << " Area: " << cv::contourArea(cv::Mat(contours[i], false)) << endl;
std::vector<std::vector<cv::Point> >::iterator itc= contours.begin();
while (itc!=contours.end()) {
if (contours[i].size()>500 || contours[i].size()<20 )
itc= contours.erase(itc);
else
++itc;
}
答案 0 :(得分:1)
问题是当您从向量contours
中删除元素时,它会减小向量的大小。索引i
从0到contours.size() - 1
,其中contours.size()
在外循环中计算。在内循环中,当您从contours
中删除元素时,contours
的大小会减少,但i
不会更新以反映轮廓的缩小。这就是为什么你得到向量下标超出范围错误。
for(unsigned int i=0;i<contours.size();i++)
{
// something else ...
std::vector<std::vector<cv::Point> >::iterator itc= contours.begin();
while (itc!=contours.end()) {
if (contours[i].size()>500 || contours[i].size()<20 ) {
itc= contours.erase(itc);
// Now contours will have one less element
// However index i has not been updated and so
// contours[i] will eventually index out of range in
// one of the subsequent iterations of this inner loop
}
else {
++itc;
}
}
}