Convert KNN train from Opencv 3 to 2

孤街浪徒 提交于 2019-12-24 05:59:42

问题


I am reading a tutorial for training KNN using Opencv. The code is written for Opencv 3 but I need to use it in Opencv 2. The original training is:

cv2.ml.KNearest_create().train(npaFlattenedImages, cv2.ml.ROW_SAMPLE, npaClassifications)

I tried using this:

cv2.KNearest().train(npaFlattenedImages, cv2.CV_ROW_SAMPLE, npaClassifications)

but the error is:

Unsupported index array data type (it should be 8uC1, 8sC1 or 32sC1) in function cvPreprocessIndexArray

The full code is here: https://github.com/MicrocontrollersAndMore/OpenCV_3_KNN_Character_Recognition_Python/blob/master/TrainAndTest.py


回答1:


Here the changes that appear to have made the full code work for me for OpenCV 2.4.13:

60c60
<     kNearest = cv2.ml.KNearest_create()                   # instantiate KNN object
---
>     kNearest = cv2.KNearest()                   # instantiate KNN object
62c62
<     kNearest.train(npaFlattenedImages, cv2.ml.ROW_SAMPLE, npaClassifications)
---
>     kNearest.train(npaFlattenedImages, npaClassifications)
85c85
<     imgContours, npaContours, npaHierarchy = cv2.findContours(imgThreshCopy,             # input image, make sure to use a copy since the function will modify this image in the course of finding contours
---
>     npaContours, npaHierarchy = cv2.findContours(imgThreshCopy,             # input image, make sure to use a copy since the function will modify this image in the course of finding contours
125c125
<         retval, npaResults, neigh_resp, dists = kNearest.findNearest(npaROIResized, k = 1)     # call KNN function find_nearest
---
>         retval, npaResults, neigh_resp, dists = kNearest.find_nearest(npaROIResized, k = 1)     # call KNN function find_nearest



回答2:


  • Unlike the generic CvStatModel::train(), cv2.KNearest.train() doesn't have the 2nd optional argument int tflag, and the docs say: "Only CV_ROW_SAMPLE data layout is supported".
    • The error message (btw the cryptic mnemonics are OpenCV data types) was thus caused by the function trying to use npaClassifications as the next argument, sampleIdx.

Further errors after fixing this:

  • cv2.findCountours() only returns 2 values: → contours, hierarchy (you don't need the 3rd one, imgContours, anyway).

  • KNearest.findNearest() was KNearest.find_nearest().

And the result now:

Ulrich Stern already did me a favor to provide a raw diff.



来源:https://stackoverflow.com/questions/39598724/convert-knn-train-from-opencv-3-to-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!