Ask Your Question

How to save ANN_MLP by appending to file containing other data?

asked 2017-10-05 09:22:36 -0600

nmcfarlane gravatar image

updated 2017-10-05 11:41:27 -0600

I'm using OpenCV 3.2. I need to save a trained ANN_MLP network, but it needs to be saved in the same file as other serialised data from the application (the api specifies only one set-up file), so I need a save() method that appends to existing data in a file.

Is there a way to save ANN_MLP by appending to an existing file and then read it back again?

Failing that, is is possible to "train" a network by setting the weight matrices, instead of using train() or load()? This would enable me to simply write/read the matrices that describe the network.

edit retag flag offensive close merge delete


I have solved the second part of this question: it is possible to create a working network by copying the matrices. The tricky part is that there is no setWeights() method, so you have to copy the weights using:


Only copyTo() will actually copy to the internal data of mlp2; assignment and clone() will not work.

nmcfarlane gravatar imagenmcfarlane ( 2017-10-05 11:29:43 -0600 )edit

this is the "back door".

what if you use


to save it, and

Ptr<ANN_MLP> new_nn = Algorithm::read<ml::ANN_MLP>(some_existing_filestorage);

to retrieve it ?

berak gravatar imageberak ( 2017-10-05 11:45:55 -0600 )edit

1 answer

Sort by » oldest newest most voted

answered 2017-10-06 06:15:15 -0600

nmcfarlane gravatar image

updated 2017-10-06 06:18:33 -0600

berak gravatar image

Thank you, berak. For info, in the simple case of writing and reading, this works:

cv::FileStorage fs;"mlp.xml", cv::FileStorage::WRITE);

mlp2 = ANN_MLP::create();"mlp.xml", cv::FileStorage::READ);

If the network is to be saved as a node in a larger hierarchy, write with:

  fs << "StructureAndWeights" << "{";
  fs << "}";

and read with:

 cv::FileNode node0 = fs.root();
 cv::FileNode node1 = node0["StructureAndWeights"];
edit flag offensive delete link more

Question Tools

1 follower


Asked: 2017-10-05 09:22:36 -0600

Seen: 362 times

Last updated: Oct 06 '17