Ask Your Question
0

Deep copy of list of instances with cv::Mat members

asked 2013-07-17 18:49:43 -0600

B. Bogart gravatar image

What is the best way to make a deep copy of a list of instances who have Mat members?

Lets say I have this class:

class myClass {
    public:
        Mat image;

        myClass(Scalar value) {
            this->image =  Mat(300, 300, CV_8UC3, value);
        }
};

I can populate a list of instances with:

instances.push_back(myClass(Scalar(0,255,0)));
instances.push_back(myClass(Scalar(0,255,255)));

Now I would like a second list that is a deep copy of the instances including the underlying Mat data. Just doing the following does a shallow copy:

list<myClass> newInstances = instances;

The problem is that I have opencv doing some vision stuff in one thread, and I want to copy the data into the main renderer such that the renderer will not keep data from being cleared in the thread.

Thanks.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2013-07-17 19:17:51 -0600

berak gravatar image

a simple

Mat a, b; 
a = b;

assignment will only copy the Mat structure, and assign b's pixel pointer to a

for a "deep copy" ( esp. of the pixels ), i think, you want

a = b.clone()

edit flag offensive delete link more

Comments

Ok, but how do I make the assignment operator for the list of instances do clone rather than assignment? I could just make a loop and manually copy, but I'm doing these operations in a lot of different places and overriding assignment for these instances would be better.

B. Bogart gravatar imageB. Bogart ( 2013-07-18 11:31:36 -0600 )edit

understandable request ;)

let me play a bit with it ..

berak gravatar imageberak ( 2013-07-18 11:53:18 -0600 )edit

nice puzzle, how far did you come there ?

could not find something real satisfying.

http://bpaste.net/show/QhIHCVrR7hq9FwsBBQpF/

berak gravatar imageberak ( 2013-07-18 13:22:07 -0600 )edit

I did not consider that overriding the assignment operator would probably cause a lot of other unintended consequences when passing around my classes. Seems a custom function that does a manual deep copy is the best way to go.

B. Bogart gravatar imageB. Bogart ( 2013-07-19 12:52:00 -0600 )edit

yes, think so, too.

berak gravatar imageberak ( 2013-07-19 12:59:08 -0600 )edit

@berak, I was about to ask this question again, to find I already had! I'm trying to replace an instance containing a mat with a new instance (or a copy of all the members), but my replacement causes a leak. using clone() does not solve the leak. Please see this post: http://stackoverflow.com/questions/18772065/how-to-replace-an-instance-with-another-instance-via-pointer

B. Bogart gravatar imageB. Bogart ( 2013-09-13 16:03:27 -0600 )edit

Question Tools

Stats

Asked: 2013-07-17 18:49:43 -0600

Seen: 1,274 times

Last updated: Jul 17 '13