OpenCV  4.1.1-pre
Open Source Computer Vision
Looking for a C++ dev who knows OpenCV?
I'm looking for work. Hire me!
cv::ml::KNearest Class Referenceabstract

The class implements K-Nearest Neighbors model. More...

#include <opencv2/ml.hpp>

Inheritance diagram for cv::ml::KNearest:
Collaboration diagram for cv::ml::KNearest:

Public Types

enum  Flags {
  UPDATE_MODEL = 1,
  RAW_OUTPUT =1,
  COMPRESSED_INPUT =2,
  PREPROCESSED_INPUT =4
}
 Predict options. More...
 
enum  Types {
  BRUTE_FORCE =1,
  KDTREE =2
}
 Implementations of KNearest algorithm. More...
 

Public Member Functions

virtual float calcError (const Ptr< TrainData > &data, bool test, OutputArray resp) const
 Computes error on the training or test dataset. More...
 
virtual void clear ()
 Clears the algorithm state. More...
 
virtual bool empty () const CV_OVERRIDE
 Returns true if the Algorithm is empty (e.g. More...
 
virtual float findNearest (InputArray samples, int k, OutputArray results, OutputArray neighborResponses=noArray(), OutputArray dist=noArray()) const =0
 Finds the neighbors and predicts responses for input vectors. More...
 
virtual int getAlgorithmType () const =0
 Algorithm type, one of KNearest::Types. More...
 
virtual int getDefaultK () const =0
 Default number of neighbors to use in predict method. More...
 
virtual String getDefaultName () const
 Returns the algorithm string identifier. More...
 
virtual int getEmax () const =0
 Parameter for KDTree implementation. More...
 
virtual bool getIsClassifier () const =0
 Whether classification or regression model should be trained. More...
 
virtual int getVarCount () const =0
 Returns the number of variables in training samples. More...
 
virtual bool isClassifier () const =0
 Returns true if the model is classifier. More...
 
virtual bool isTrained () const =0
 Returns true if the model is trained. More...
 
virtual float predict (InputArray samples, OutputArray results=noArray(), int flags=0) const =0
 Predicts response(s) for the provided sample(s) More...
 
virtual void read (const FileNode &fn)
 Reads algorithm parameters from a file storage. More...
 
virtual void save (const String &filename) const
 Saves the algorithm to a file. More...
 
virtual void setAlgorithmType (int val)=0
 Algorithm type, one of KNearest::Types. More...
 
virtual void setDefaultK (int val)=0
 Default number of neighbors to use in predict method. More...
 
virtual void setEmax (int val)=0
 Parameter for KDTree implementation. More...
 
virtual void setIsClassifier (bool val)=0
 Whether classification or regression model should be trained. More...
 
virtual bool train (const Ptr< TrainData > &trainData, int flags=0)
 Trains the statistical model. More...
 
virtual bool train (InputArray samples, int layout, InputArray responses)
 Trains the statistical model. More...
 
virtual void write (FileStorage &fs) const
 Stores algorithm parameters in a file storage. More...
 
void write (const Ptr< FileStorage > &fs, const String &name=String()) const
 simplified API for language bindings This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 

Static Public Member Functions

static Ptr< KNearestcreate ()
 Creates the empty model. More...
 
static Ptr< KNearestload (const String &filepath)
 Loads and creates a serialized knearest from a file. More...
 
template<typename _Tp >
static Ptr< _Tp > load (const String &filename, const String &objname=String())
 Loads algorithm from the file. More...
 
template<typename _Tp >
static Ptr< _Tp > loadFromString (const String &strModel, const String &objname=String())
 Loads algorithm from a String. More...
 
template<typename _Tp >
static Ptr< _Tp > read (const FileNode &fn)
 Reads algorithm from the file node. More...
 
template<typename _Tp >
static Ptr< _Tp > train (const Ptr< TrainData > &data, int flags=0)
 Create and train model with default parameters. More...
 

Protected Member Functions

void writeFormat (FileStorage &fs) const
 

Detailed Description

The class implements K-Nearest Neighbors model.

See also
K-Nearest Neighbors

Member Enumeration Documentation

◆ Flags

enum cv::ml::StatModel::Flags
inherited

Predict options.

Enumerator
UPDATE_MODEL 
RAW_OUTPUT 

makes the method return the raw results (the sum), not the class label

COMPRESSED_INPUT 
PREPROCESSED_INPUT 

◆ Types

Implementations of KNearest algorithm.

Enumerator
BRUTE_FORCE 
KDTREE 

Member Function Documentation

◆ calcError()

virtual float cv::ml::StatModel::calcError ( const Ptr< TrainData > &  data,
bool  test,
OutputArray  resp 
) const
virtualinherited

Computes error on the training or test dataset.

Parameters
datathe training data
testif true, the error is computed over the test subset of the data, otherwise it's computed over the training subset of the data. Please note that if you loaded a completely different dataset to evaluate already trained classifier, you will probably want not to set the test subset at all with TrainData::setTrainTestSplitRatio and specify test=false, so that the error is computed for the whole new set. Yes, this sounds a bit confusing.
respthe optional output responses.

The method uses StatModel::predict to compute the error. For regression models the error is computed as RMS, for classifiers - as a percent of missclassified samples (0%-100%).

◆ clear()

virtual void cv::Algorithm::clear ( )
inlinevirtualinherited

Clears the algorithm state.

Reimplemented in cv::FlannBasedMatcher, and cv::DescriptorMatcher.

◆ create()

static Ptr<KNearest> cv::ml::KNearest::create ( )
static

Creates the empty model.

The static method creates empty KNearest classifier. It should be then trained using StatModel::train method.

◆ empty()

virtual bool cv::ml::StatModel::empty ( ) const
virtualinherited

Returns true if the Algorithm is empty (e.g.

in the very beginning or after unsuccessful read

Reimplemented from cv::Algorithm.

◆ findNearest()

virtual float cv::ml::KNearest::findNearest ( InputArray  samples,
int  k,
OutputArray  results,
OutputArray  neighborResponses = noArray(),
OutputArray  dist = noArray() 
) const
pure virtual

Finds the neighbors and predicts responses for input vectors.

Parameters
samplesInput samples stored by rows. It is a single-precision floating-point matrix of <number_of_samples> * k size.
kNumber of used nearest neighbors. Should be greater than 1.
resultsVector with results of prediction (regression or classification) for each input sample. It is a single-precision floating-point vector with <number_of_samples> elements.
neighborResponsesOptional output values for corresponding neighbors. It is a single- precision floating-point matrix of <number_of_samples> * k size.
distOptional output distances from the input vectors to the corresponding neighbors. It is a single-precision floating-point matrix of <number_of_samples> * k size.

For each input vector (a row of the matrix samples), the method finds the k nearest neighbors. In case of regression, the predicted result is a mean value of the particular vector's neighbor responses. In case of classification, the class is determined by voting.

For each input vector, the neighbors are sorted by their distances to the vector.

In case of C++ interface you can use output pointers to empty matrices and the function will allocate memory itself.

If only a single input vector is passed, all output matrices are optional and the predicted value is returned by the method.

The function is parallelized with the TBB library.

◆ getAlgorithmType()

virtual int cv::ml::KNearest::getAlgorithmType ( ) const
pure virtual

Algorithm type, one of KNearest::Types.

See also
setAlgorithmType

◆ getDefaultK()

virtual int cv::ml::KNearest::getDefaultK ( ) const
pure virtual

Default number of neighbors to use in predict method.

See also
setDefaultK

◆ getDefaultName()

virtual String cv::Algorithm::getDefaultName ( ) const
virtualinherited

Returns the algorithm string identifier.

This string is used as top level xml/yml node tag when the object is saved to a file or string.

Reimplemented in cv::AKAZE, cv::KAZE, cv::SimpleBlobDetector, cv::GFTTDetector, cv::AgastFeatureDetector, cv::FastFeatureDetector, cv::MSER, cv::ORB, cv::BRISK, and cv::Feature2D.

◆ getEmax()

virtual int cv::ml::KNearest::getEmax ( ) const
pure virtual

Parameter for KDTree implementation.

See also
setEmax

◆ getIsClassifier()

virtual bool cv::ml::KNearest::getIsClassifier ( ) const
pure virtual

Whether classification or regression model should be trained.

See also
setIsClassifier

◆ getVarCount()

virtual int cv::ml::StatModel::getVarCount ( ) const
pure virtualinherited

Returns the number of variables in training samples.

◆ isClassifier()

virtual bool cv::ml::StatModel::isClassifier ( ) const
pure virtualinherited

Returns true if the model is classifier.

◆ isTrained()

virtual bool cv::ml::StatModel::isTrained ( ) const
pure virtualinherited

Returns true if the model is trained.

◆ load() [1/2]

static Ptr<KNearest> cv::ml::KNearest::load ( const String filepath)
static

Loads and creates a serialized knearest from a file.

Use KNearest::save to serialize and store an KNearest to disk. Load the KNearest from this file again, by calling this function with the path to the file.

Parameters
filepathpath to serialized KNearest

◆ load() [2/2]

template<typename _Tp >
static Ptr<_Tp> cv::Algorithm::load ( const String filename,
const String objname = String() 
)
inlinestaticinherited

Loads algorithm from the file.

Parameters
filenameName of the file to read.
objnameThe optional name of the node to read (if empty, the first top-level node will be used)

This is static template method of Algorithm. It's usage is following (in the case of SVM):

Ptr<SVM> svm = Algorithm::load<SVM>("my_svm_model.xml");

In order to make this method work, the derived class must overwrite Algorithm::read(const FileNode& fn).

References CV_Assert, cv::FileNode::empty(), cv::FileStorage::getFirstTopLevelNode(), cv::FileStorage::isOpened(), and cv::FileStorage::READ.

Here is the call graph for this function:

◆ loadFromString()

template<typename _Tp >
static Ptr<_Tp> cv::Algorithm::loadFromString ( const String strModel,
const String objname = String() 
)
inlinestaticinherited

Loads algorithm from a String.

Parameters
strModelThe string variable containing the model you want to load.
objnameThe optional name of the node to read (if empty, the first top-level node will be used)

This is static template method of Algorithm. It's usage is following (in the case of SVM):

Ptr<SVM> svm = Algorithm::loadFromString<SVM>(myStringModel);

References CV_WRAP, cv::FileNode::empty(), cv::FileStorage::getFirstTopLevelNode(), cv::FileStorage::MEMORY, and cv::FileStorage::READ.

Here is the call graph for this function:

◆ predict()

virtual float cv::ml::StatModel::predict ( InputArray  samples,
OutputArray  results = noArray(),
int  flags = 0 
) const
pure virtualinherited

Predicts response(s) for the provided sample(s)

Parameters
samplesThe input samples, floating-point matrix
resultsThe optional output matrix of results.
flagsThe optional flags, model-dependent. See cv::ml::StatModel::Flags.

Implemented in cv::ml::LogisticRegression, and cv::ml::EM.

◆ read() [1/2]

virtual void cv::Algorithm::read ( const FileNode fn)
inlinevirtualinherited

Reads algorithm parameters from a file storage.

Reimplemented in cv::FlannBasedMatcher, cv::DescriptorMatcher, and cv::Feature2D.

◆ read() [2/2]

template<typename _Tp >
static Ptr<_Tp> cv::Algorithm::read ( const FileNode fn)
inlinestaticinherited

Reads algorithm from the file node.

This is static template method of Algorithm. It's usage is following (in the case of SVM):

cv::FileStorage fsRead("example.xml", FileStorage::READ);
Ptr<SVM> svm = Algorithm::read<SVM>(fsRead.root());

In order to make this method work, the derived class must overwrite Algorithm::read(const FileNode& fn) and also have static create() method without parameters (or with all the optional parameters)

◆ save()

virtual void cv::Algorithm::save ( const String filename) const
virtualinherited

Saves the algorithm to a file.

In order to make this method work, the derived class must implement Algorithm::write(FileStorage& fs).

◆ setAlgorithmType()

virtual void cv::ml::KNearest::setAlgorithmType ( int  val)
pure virtual

Algorithm type, one of KNearest::Types.

See also
getAlgorithmType

◆ setDefaultK()

virtual void cv::ml::KNearest::setDefaultK ( int  val)
pure virtual

Default number of neighbors to use in predict method.

See also
getDefaultK

◆ setEmax()

virtual void cv::ml::KNearest::setEmax ( int  val)
pure virtual

Parameter for KDTree implementation.

See also
getEmax

◆ setIsClassifier()

virtual void cv::ml::KNearest::setIsClassifier ( bool  val)
pure virtual

Whether classification or regression model should be trained.

See also
getIsClassifier

◆ train() [1/3]

virtual bool cv::ml::StatModel::train ( const Ptr< TrainData > &  trainData,
int  flags = 0 
)
virtualinherited

Trains the statistical model.

Parameters
trainDatatraining data that can be loaded from file using TrainData::loadFromCSV or created with TrainData::create.
flagsoptional flags, depending on the model. Some of the models can be updated with the new training samples, not completely overwritten (such as NormalBayesClassifier or ANN_MLP).

◆ train() [2/3]

virtual bool cv::ml::StatModel::train ( InputArray  samples,
int  layout,
InputArray  responses 
)
virtualinherited

Trains the statistical model.

Parameters
samplestraining samples
layoutSee ml::SampleTypes.
responsesvector of responses associated with the training samples.

◆ train() [3/3]

template<typename _Tp >
static Ptr<_Tp> cv::ml::StatModel::train ( const Ptr< TrainData > &  data,
int  flags = 0 
)
inlinestaticinherited

Create and train model with default parameters.

The class must implement static create() method with no parameters or with all default parameter values

◆ write() [1/2]

virtual void cv::Algorithm::write ( FileStorage fs) const
inlinevirtualinherited

Stores algorithm parameters in a file storage.

Reimplemented in cv::FlannBasedMatcher, cv::DescriptorMatcher, and cv::Feature2D.

References CV_WRAP.

Referenced by cv::Feature2D::write(), and cv::DescriptorMatcher::write().

Here is the caller graph for this function:

◆ write() [2/2]

void cv::Algorithm::write ( const Ptr< FileStorage > &  fs,
const String name = String() 
) const
inherited

simplified API for language bindings This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ writeFormat()

void cv::Algorithm::writeFormat ( FileStorage fs) const
protectedinherited

The documentation for this class was generated from the following file: