This notebook contains an excerpt from the book Machine Learning for OpenCV by Michael Beyeler. The code is released under the MIT license, and is available on GitHub.

Note that this excerpt contains only the raw code - the book is rich with additional explanations and illustrations. If you find this content useful, please consider supporting the work by buying the book!

Dealing with Data Using OpenCV's TrainData Container in C++

For the sake of completeness, and for those who insist on using the C++ API of OpenCV, let's do a quick detour on OpenCV's TrainData container that allows us to load numerical data from .csv files.

Among other things, in C++ the ml module contains a class called TrainData, which provides a container to work with data in C++. Its functionality is limited to reading (preferably) numerical data from .csv files (containing comma-separated values). Hence, if the data that you want to work with comes in a neatly organized .csv file, this class will save you a lot of time. If your data comes from a different source, I'm afraid your best option might be to create a .csv file by hand, using a suitable program such as Open Office or Microsoft Excel.

If you have some nice all-float data that lives in a comma-separated file, you could load it like so:

Ptr<TrainData> tDataContainer = TrainData::loadFromCSV("file.csv",
                                    0,  // number of lines to skip
                                    0); // index of 1st and only output var

Shuffling data is easy:

tDataContainer->shuffleTrainTest();

And so is splitting data into training and test sets. For example, if your file contains 100 samples, you could assign the first 90 samples to the training set, and leave the remaining 10 to the test set:

tDataContainer->setTrainTestSplit(90);

You can also load all training/test samples and store them in an OpenCV matrix:

cv::Mat trainData = tDataContainer->getTrainSamples();
cv::Mat testData = tDataContainer->getTestSamples();

Most OpenCV classifiers from the ml module then directly take training data as an input. Let's say you have a statistical model saved in the variable model:

model->train(tDataContainer->getTrainSamples());

You can find all relevant functions described here: http://docs.opencv.org/3.1.0/dc/d32/classcv_1_1ml_1_1TrainData.html.

Other than that, I'm afraid the TrainData container and its use cases might be a bit antiquated. So for the rest of the book, we will focus on Python instead.