標籤:des style color io strong 資料 for ar
當我們想要將一個Mat對象的資料複製給另一個Mat對象時,應該怎麼做呢?
我們發現,OpenCV提供了重載運算子Mat::operator = ,那麼,是否按照下列語句就可以輕鬆完成對象的賦值呢?
Mat a;Mat b = a;
答案是否定的!
我們可以從reference manual 中看到:
Mat::operator =
Provides matrix assignment operators.
C++: Mat& Mat::operator=(const Mat& m)
Parameters
m – Assigned, right-hand-side matrix. Matrix assignment is an O(1) operation. This means that no data is copied but the data is shared and the reference counter, if any, is incremented. Before assigning new data, the old data is de-referenced via Mat::release() .
這意味著,操作之後,b與a將共用同一片資料,不會發生資料的複製。
同樣,我們可以從原始碼中看出:
inline Mat& Mat::operator = (const Mat& m){ if( this != &m ) { if( m.refcount ) CV_XADD(m.refcount, 1); release(); flags = m.flags; if( dims <= 2 && m.dims <= 2 ) { dims = m.dims; rows = m.rows; cols = m.cols; step[0] = m.step[0]; step[1] = m.step[1]; } else copySize(m); data = m.data; datastart = m.datastart; dataend = m.dataend; datalimit = m.datalimit; refcount = m.refcount; allocator = m.allocator; } return *this;}該重載運算子只是將各個資料指標的地址進行了賦值,並沒有複製資料的操作。
那麼如果我們需要複製Mat對象,應該如何操作呢?
(1)Mat::copyTo函數
Mat a;Mat b;a.copyTo(b);
(2)Mat::clone函數
Mat a;Mat b = a.clone();
那麼,這兩個函數有什麼區別呢?
我們查看原始碼:
inline Mat Mat::clone() const{ Mat m; copyTo(m); return m;}
從原始碼可以發現,其實clone()函數就是copyTo()的另一個實現而已。