Ask Your Question
4

Mat clone or just assignement?

asked 2014-08-05 08:57:02 -0500

thdrksdfthmn gravatar image

updated 2014-08-07 10:08:37 -0500

I have a class that has a member of type Mat. I am doing some operation on the input image parameter and saving the image after step X in that member and returning the image after step Y. My problem is how to do it better:

  1. assigning the step X image to the member; or
  2. assigning the clone of step X image to the member?

The code is something like:

class Processing
{
private:
  cv::Mat m_img;

public:
  cv::Mat getImg() const { return m_img; }
  cv::Mat binarization(const cv::Mat& imgIn)
  {
    cv::Mat img2;
    processing1(imgIn, img2);
    processing2(img2, img2);
    m_img = img2.clone(); // or
    // m_img = img2;
    processing3(img2, img2);
    return img2;
  }
};

I am not sure if I do the second operation (assignment) is ok regarding the data. Any suggestions?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
4

answered 2014-08-06 06:45:12 -0500

boaz001 gravatar image

Since you do not provide details about what processing1, processing2 and processing3 do. Just to be safe you can use a clone().

For performance reasons you don't want to use clone because it copies all data instead of passing a reference to the data.

On a functional level it depends on what processing3 does, does it change the data one of it's inputs? Then in the case of the assignment img2 and m_img point to the same data. And are both changed. And I don't know if that is what you want...

Read this for more background info.

edit flag offensive delete link more

Comments

Supposing that processingX is not changing the data in the first parameter, if I do an assignment, the matrix data will not be freed until the last header pointing to it is freed?

thdrksdfthmn gravatar imagethdrksdfthmn ( 2014-08-06 07:22:45 -0500 )edit

Don't think about reserving/freeing data too much. OpenCV generally does this all for you. Only thing you must keep in mind is that assignment and copying takes a reference of the actual data. Since a reference is just another name for the same thing. Modifying one reference will change the data on one place, but there could be many references pointing to that changed data.

boaz001 gravatar imageboaz001 ( 2014-08-06 09:49:33 -0500 )edit

This is what I am asking: What are the probability of changing m_img after exiting the function, if I use m_img = img2;? img2 is not changing. Or another one: Is there a possibility to change initial image if I do binarization(imgInit(someROI));?

thdrksdfthmn gravatar imagethdrksdfthmn ( 2014-08-07 10:14:43 -0500 )edit
Login/Signup to Answer

Question Tools

Stats

Asked: 2014-08-05 08:57:02 -0500

Seen: 352 times

Last updated: Aug 07 '14