Ask Your Question

Revision history [back]

Mat::clone and Mat::operator =

Similar questions have been raised, but I am still unsure, when to use clone and when to use = operator. clone makes a full copy, whereas = creates a new header only, but shares the pixel data. Does this mean that in Example 1, the pixel data of image are modified and visible to the caller? If yes, I have to clone the image, where the image by the caller is preserved, as in Example 2?

Example 1:

void GFTTDetector::detectImpl( const Mat& image, std::vector<KeyPoint>& keypoints, const Mat& mask) const
{
    Mat grayImage = image;
    if( image.type() != CV_8U ) cvtColor( image, grayImage, COLOR_BGR2GRAY );
    ...
}

Example 2:

void GFTTDetector::detectImpl( const Mat& image, std::vector<KeyPoint>& keypoints, const Mat& mask) const
{
    Mat grayImage = image.clone();
    if( image.type() != CV_8U ) cvtColor( image, grayImage, COLOR_BGR2GRAY );
    ...
}