Writing your own OpenCV-based classifier in C++

Since OpenCV is one of those Python libraries that does not contain a single line of Python code under the hood (I'm kidding, but it's close), you will have to implement your custom estimator in C++. This can be done in four steps:

  1. Implement a C++ source file that contains the main source code. You need to include two header files, one that contains all the core functionality of OpenCV (opencv.hpp) and another that contains the machine learning module (ml.hpp):
#include <opencv2/opencv.hpp>
#include <opencv2/ml/ml.hpp>
#include <stdio.h>

Then, an estimator class can be created by inheriting from the StatModel class:

class MyClass : public cv::ml::StatModel
{
public:

Next, you define constructor and destructor of the class:

MyClass()
{
print("MyClass constructor ");
}
~MyClass() {}

Then, you also have to define some methods. These are what you would fill in to make the classifier actually do some work:

int getVarCount() const
{
// returns the number of variables in training samples
return 0;
}

bool empty() const
{
return true;
}

bool isTrained() const
{
// returns true if the model is trained
return false;
}

bool isClassifier() const
{
// returns true if the model is a classifier
return true;
}

The main work is done in the train method, which comes in two flavors (accepting either cv::ml::TrainData or cv::InputArray as input):

bool train(const cv::Ptr<cv::ml::TrainData>& trainData,
int flags=0) const
{
// trains the model
return false;
}

bool train(cv::InputArray samples, int layout,
cv::InputArray responses)
{
// trains the model
return false;
}

You also need to provide a predict method and a scoring function:

        float predict(cv::InputArray samples,
cv::OutputArray results=cv::noArray(),
int flags=0) const
{
// predicts responses for the provided samples
return 0.0f;
}

float calcError(const cv::Ptr<cv::ml::TrainData>& data,
bool test, cv::OutputArray resp)
{
// calculates the error on the training or test dataset
return 0.0f;
}
};

The last thing to do is to include a main function that instantiates the class:

   int main()
{
MyClass myclass;
return 0;
}
  1. Write a CMake file called CMakeLists.txt:
cmake_minimum_required(VERSION 2.8)
project(MyClass)
find_package(OpenCV REQUIRED)
add_executable(MyClass MyClass.cpp)
target_link_libraries(MyClass ${OpenCV_LIBS})
  1. Compile the file on the command line by typing the following commands:
$ cmake
$ make
  1. Run the executable MyClass method, which was generated by the last command and which should lead to the following output:
$ ./MyClass
MyClass constructor
..................Content has been hidden....................

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