2013-05-31 135 views
0

當我運行下面的代碼我得到這個例外矢量下標超出範圍,該代碼成功地工作沒有例外的圖像上,但是當我改變的圖像發生異常。矢量標超出範圍C++誤差

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

什麼'i'?您可以將其包含在此代碼段中,而不必提及它是什麼或來自哪裏。你應該在這裏使用迭代器而不是直接的下標訪問。 – mwigdahl

+0

你在哪裏設置'我'? – Barmar

+0

我是要找到的輪廓點#圖像中我嘗試過的圖像上的代碼無一例外但是當我改變形象它給了我矢量下標越界異常 – shahd

回答

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

非常感謝你的圖像工作,但有些圖像它沒有工作 – shahd

+0

你是如何解決爲問題 – Alexey

+0

(無符號整數,I = 0; I <輪廓[I] .size();我++)? { \t \t的std ::矢量<性病::矢量>:迭代ITC = contours.begin() ;(!ITC = contours.end()) \t \t \t \t 而{ 如果(輪廓[I] .size()> 500個||輪廓[I] .size()<50) ITC =輪廓。擦除(itc); else ++ itc; }} 的 – shahd