2013-02-03 145 views
0

我有一個向量向量Point(稱爲squares,返回findSquares()函數squares.cpp(OpenCV))。如何讀取向量的向量點 - C++

我想做一個平均的四點存儲在點的向量(在c + +語言)的x和y座標。

我試着這樣做:

vector <Point> coordinates(4); 

    for (int i = 0; i<squares.size();i++) { 

     coordinates[0].x += squares[i][0].x; 
     coordinates[0].y += squares[i][0].y; 

     coordinates[1].x += squares[i][1].x; 
     coordinates[1].y += squares[i][1].y; 

     coordinates[2].x += squares[i][2].x; 
     coordinates[2].y += squares[i][2].y; 

     coordinates[3].x += squares[i][3].x; 
     coordinates[3].y += squares[i][3].y; 
    } 
    if(squares.size() !=0){ 
     for(int j=0; j<4; j++) { 
      coordinates[j].x /= squares.size(); 
      coordinates[j].y /= squares.size(); 
     } 
    } 

,但我得到這個異常:

以錯誤的方式點的矢量的矢量的

enter image description here

我讀的元素?

+0

你可以顯示創建「方塊」的程序嗎? –

+0

'vector > squares; findSquares(image,squares);' 您可以在此鏈接找到'findSquares(...)'函數:[https://projects.developer.nokia.com/opencv/browser/opencv/opencv-2.3。 1/samples/cpp/squares.cpp] – Cristina1986

+0

安迪的意思是:你如何填補正方形?或者你不填充這個矢量?我認爲這是我們必須看到的findSquares()函數。 – leemes

回答

2

,請注意下面的代碼:

if (squares.size() !=0){ 
    for(int j=0; j<4; j++) { 
     coordinates[j].x /= squares.size(); 
     coordinates[j].y /= squares.size(); 
    } 
} 

這個代碼塊可以在coordinates[j].x崩潰時squares.size()大於0但小於4

試想一下,squares.size()是2.什麼當j變成2時,你認爲它會在for循環中發生嗎?該部門將變爲coordinates[2].x /= squares.size();,該部門試圖訪問不存在的向量中的位置,導致崩潰。 請記住:如果數組大小爲2,則向量的有效索引爲0和1,所以2超出範圍。

這是您的代碼中的問題,可能是導致崩潰的原因。修復它更新您的循環是:

for (int j = 0; j < squares.size(); j++) { 

如果崩潰繼續發生,問題在於您的代碼中的其他地方。