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

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

最佳答案

问题是,当您从 vector contours中删除一个元素时,它会减小 vector 的大小。索引i从0到contours.size() - 1,其中contours.size()在外部循环中计算。在内部循环中,当您从contours中删除元素时,contours的大小将减小,但是i不会更新以反射(reflect)轮廓线减小的大小。这就是为什么 vector 下标超出范围错误的原因。

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

关于visual-c++ - 向量下标超出范围C++错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16861260/

10-11 19:08