Skip to content

Commit

Permalink
Add Ptr KNearest::load and python binding
Browse files Browse the repository at this point in the history
  • Loading branch information
LaurentBerger committed Apr 16, 2019
1 parent c9a76ed commit 621e3ea
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
8 changes: 8 additions & 0 deletions modules/ml/include/opencv2/ml.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,14 @@ class CV_EXPORTS_W KNearest : public StatModel
The static method creates empty %KNearest classifier. It should be then trained using StatModel::train method.
*/
CV_WRAP static Ptr<KNearest> create();
/** @brief 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.
*
* @param filepath path to serialized KNearest
*/
CV_WRAP static Ptr<KNearest> load(const String& filepath);
};

/****************************************************************************************\
Expand Down
13 changes: 13 additions & 0 deletions modules/ml/misc/python/test/test_knearest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#!/usr/bin/env python
import cv2 as cv

from tests_common import NewOpenCVTests

class knearest_test(NewOpenCVTests):
def test_load(self):
k_nearest = cv.ml.KNearest_load(self.find_file("ml/opencv_ml_knn.xml"))
self.assertFalse(k_nearest.empty())
self.assertTrue(k_nearest.isTrained())

if __name__ == '__main__':
NewOpenCVTests.bootstrap()
11 changes: 11 additions & 0 deletions modules/ml/src/knearest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,17 @@ Ptr<KNearest> KNearest::create()
return makePtr<KNearestImpl>();
}

Ptr<KNearest> KNearest::load(const String& filepath)
{
FileStorage fs;
fs.open(filepath, FileStorage::READ);

Ptr<KNearest> knearest = makePtr<KNearestImpl>();

((KNearestImpl*)knearest.get())->read(fs.getFirstTopLevelNode());
return knearest;
}

}
}

Expand Down

0 comments on commit 621e3ea

Please sign in to comment.