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, which 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 OpenOffice or Microsoft Excel.

The most important method of the TrainData class is called loadFromCSV, which accepts the following parameters:

  • const String& filename: The input filename
  • int headerLineCount: The number of lines in the beginning to skip
  • int responseStartIdx: The index of the first output variable
  • int responseEndIdx: The index of the last output variable
  • const String& varTypeSpec: A text string describing the data type of all output variables
  • char delimiter: The character used to separate values in each line
  • char missch: The character used to specify missing measurements

If you have some nice all-float data that lives in a comma-separated file, you can load it as follows:

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

The class provides several handy functions to split the data into training and test sets and access individual data points in the training or 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. First, it might be a good idea to shuffle the samples:

tDataContainer->shuffleTrainTest();
tDataContainer->setTrainTestSplit(90);

Then, it is easy to store all training samples in an OpenCV matrix:

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

You can find all of the relevant functions described here: https://docs.opencv.org/4.0.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 this book, we will focus on Python instead.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.13.192