0

当我运行以下代码时,我得到此异常向量下标超出范围,此代码在图像上成功运行,没有异常,但是当我更改图像时发生异常。

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;
    }   
4

1 回答 1

2

问题是当你从向量中删除一个元素时,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;
        }
    } 
}
于 2013-05-31T18:06:54.927 回答