2012-04-26 37 views
4

我知道很多關於這個參數的帖子,我已經閱讀了很多帖子,但是我仍然感到困惑。問題是類型(哎呀,該死的,這是C,我不得不處理數據類型!;-))。在cv :: Mat中使用C++ api訪問元素(x,y)

我使用新的過冷模板C++ API函數at

Mat mat32f(3, 3, CV_32F); 
for(int i=0; i<3; i++) 
    for(int j=0; j<3; j++) 
     mat32f.at<float>(i,j) = i; 
cout << "Matrix of type: " << mat32f.type() << endl; 
cout << mat32f << endl; 
cout << mat32f.at<float>(1,2) << endl; 

OK,這裏有浮動與1路,沒問題,輸出是明確的:

Matrix of type: 5 
[0, 0, 0; 
    1, 1, 1; 
    2, 2, 2] 
1 

現在只是讓一些過濾器:

Mat mask; 
inRange(mat32f, 1, 1, mask); 
cout << "Mask of type: " << mask.type() << endl; 
cout << mask << endl; 

對於這裏,alles klar,輸出正是我想要的:

Mask of type: 0 
[0, 0, 0; 
    255, 255, 255; 
    0, 0, 0] 

現在我想檢查一下某個點(鼠標點擊嗎?不管)在範圍內。

int value2 = mask.at<char>(1,2); 
cout << value2 << endl; 
unsigned int value3 = mask.at<unsigned int>(1,2); 
cout << value3 << endl; 

我從第一臺計算機科學類,一charunsigned int相同大小的(因爲我的面具型的是0 == CV_8U)記得那麼使用字符。但cout抓住它的字符,所以讓我看看一些無用的非ASCII符號,所以把它存儲在int

這裏的輸出中:

-1 
256 

發生了什麼?一團糟。爲什麼-1?或者,再說一次,爲什麼256?發生了什麼?你是從Mat<float>得到什麼,當你使用at<char>at<unsigned int>可能是不確定的行爲(無論是由C

// template methods for read-write or read-only element access. 
// note that _Tp must match the actual matrix type - 
// the functions do not do any on-fly type conversion 

所以++:

+0

char的大小與unsigned int的大小並不相同。 – juanchopanza 2012-04-26 14:14:28

回答

3

的從OpenCV::Basic Structures狀態這一下墊::在<>()評論的方法或Open庫)。

你的聲明「一個字符的大小與unsigned int相同」也幾乎總是不正確。我相信在C++中sizeof(char) == sizeof(unsigned int)在技術上是可行的,但我不知道這是真的平臺/實現。即使在你的情況下是真的,使用這個假設也是危險的,因爲它可能不適用於你的代碼可能運行的所有系統。

更多詳細

按照OpenCV v2.4 Source和Mat ::在()看起來像(少調試代碼):

template<typename _Tp> inline const _Tp& Mat::at(int i0, int i1) const 
{ 
    return ((const _Tp*)(data + step.p[0]*i0))[i1]; 
} 

如果您嘗試訪問該類型錯誤的數據你將原始數組轉換爲錯誤的類型,這隻會導致不好的結果。

至於爲什麼你會指定數據類型而墊在::(),你就不能這樣做:

mat32f.at(i,j) = i; 

,讓編譯器自動選擇正確的模板類型?

+0

如果有人需要知道矩陣類型,那麼有什麼想法在()上模板化的點是什麼? – juanchopanza 2012-04-26 14:55:37

+0

好吧,但爲什麼也與unsigned int我不會得到255,但256? – nkint 2012-04-26 15:02:33

+0

@nkint如果在執行時沒有進行動態類型轉換,我假設他們只是將有些位從有符號的浮點數轉換爲無符號整數。基本上,這是一個危險的construction,我認爲C++ API的原因是什麼,但超酷:-) – juanchopanza 2012-04-26 15:12:52