Convert KNN train from Opencv 3 to 2
<p>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:</p>

<pre><code>cv2.ml.KNearest_create().train(npaFlattenedImages, cv2.ml.ROW_SAMPLE, npaClassifications)
</code></pre>

<p>I tried using this:</p>

<pre><code>cv2.KNearest().train(npaFlattenedImages, cv2.CV_ROW_SAMPLE, npaClassifications)
</code></pre>

<p>but the error is:</p>

<p><code>Unsupported index array data type (it should be 8uC1, 8sC1 or 32sC1) in function cvPreprocessIndexArray</code></p>

<p>The full code is here:
<a href="https://github.com/MicrocontrollersAndMore/OpenCV_3_KNN_Character_Recognition_Python/blob/master/TrainAndTest.py" rel="nofollow">https://github.com/MicrocontrollersAndMore/OpenCV_3_KNN_Character_Recognition_Python/blob/master/TrainAndTest.py</a></p>

<p>Here the changes that appear to have made the <a href="https://github.com/MicrocontrollersAndMore/OpenCV_3_KNN_Character_Recognition_Python/blob/master/TrainAndTest.py" rel="nofollow">full code</a> work for me for OpenCV 2.4.13:</p>

<pre><code>60c60
&lt;     kNearest = cv2.ml.KNearest_create()                   # instantiate KNN object
---
&gt;     kNearest = cv2.KNearest()                   # instantiate KNN object
62c62
&lt;     kNearest.train(npaFlattenedImages, cv2.ml.ROW_SAMPLE, npaClassifications)
---
&gt;     kNearest.train(npaFlattenedImages, npaClassifications)
85c85
&lt;     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
---
&gt;     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
&lt;         retval, npaResults, neigh_resp, dists = kNearest.findNearest(npaROIResized, k = 1)     # call KNN function find_nearest
---
&gt;         retval, npaResults, neigh_resp, dists = kNearest.find_nearest(npaROIResized, k = 1)     # call KNN function find_nearest
</code></pre>

python python-2.7 opencv opencv3.0