官术网_书友最值得收藏!

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.

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 a number of handy functions to split the data into training and test sets and access individual data points in the training or test set. 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 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.

主站蜘蛛池模板: 鲁山县| 固安县| 桃园县| 全州县| 慈利县| 德惠市| 民乐县| 名山县| 潞西市| 鹤壁市| 澳门| 雷州市| 九龙坡区| 加查县| 石渠县| 屏边| 无为县| 永善县| 江城| 靖远县| 南昌市| 黑河市| 崇仁县| 旌德县| 当雄县| 习水县| 丹巴县| 济阳县| 广东省| 安达市| 自贡市| 同心县| 广昌县| 新竹县| 两当县| 长乐市| 屯昌县| 温宿县| 大余县| 洞头县| 牙克石市|