OpenCV(C++介面)學習筆記4-Mat::operator = 的陷阱

來源:互聯網
上載者:User

標籤: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()的另一個實現而已。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.