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>

<ul>
<li>Unlike the generic <a href="http://docs.opencv.org/2.4/modules/ml/doc/statistical_models.html#bool%20CvStatModel::train%28const%20Mat&amp;%20train_data,%20[int%20tflag,]%20...,%20const%20Mat&amp;%20responses,%20...,%20[const%20Mat&amp;%20var_idx,]%20...,%20[const%20Mat&amp;%20sample_idx,]%20...%20[const%20Mat&amp;%20var_type,]%20...,%20[const%20Mat&amp;%20missing_mask,]%20%3Cmisc_training_alg_params%3E%20...%29" rel="nofollow"><code>CvStatModel::train()</code></a>, <a href="http://docs.opencv.org/2.4/modules/ml/doc/k_nearest_neighbors.html?highlight=cv_row_sample#cv2.KNearest.train" rel="nofollow"><code>cv2.KNearest.train()</code></a> doesn't have the 2nd optional argument <code>int tflag</code>, and the docs say: "Only <code>CV_ROW_SAMPLE</code> data layout is supported".

<ul>
<li>The error message (btw the cryptic mnemonics are <a href="http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#datatype" rel="nofollow">OpenCV data types</a>) was thus caused by the function trying to use <code>npaClassifications</code> as the next argument, <code>sampleIdx</code>.</li>
</ul></li>
</ul>

<p>Further errors after fixing this:</p>

<ul>
<li><p><a href="http://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours#cv2.findContours" rel="nofollow"><code>cv2.findCountours()</code></a> only returns 2 values: <code>â contours, hierarchy</code> (you don't need the 3rd one, <code>imgContours</code>, anyway).</p></li>
<li><p><code>KNearest.findNearest()</code> was <a href="http://docs.opencv.org/2.4/modules/ml/doc/k_nearest_neighbors.html?highlight=find%20nearest#cv2.KNearest.find_nearest" rel="nofollow"><code>KNearest.find_nearest()</code></a>.</p></li>
</ul>

<p>And the result now:</p>

<p><a href="http://i.stack.imgur.com/I2hsI.png" rel="nofollow"><img src="http://i.stack.imgur.com/I2hsI.png" alt="result"></a></p>

<p><a href="http://stackoverflow.com/a/39684278/648265">Ulrich Stern already did me a favor to provide a raw diff</a>.</p>

python python-2.7 opencv opencv3.0