KNN train() in cv2 with opencv 3.0
You are passing wrong length of array for KNN algorithm....glancing at your code, i found that you have missed the cv2.ml.ROW_SAMPLE parameter in knn.train function, passing this parameter considers the length of array as 1 for entire row. thus your corrected code would be as below:
import cv2import numpy as npimport matplotlib.pyplot as plttrainData = np.random.randint(0,100,(51,2)).astype(np.float32)responses = np.random.randint(0,2,(51,1)).astype(np.float32)red = trainData[responses.ravel()==0]plt.scatter(red[:,0],red[:,1],80,'r','^')blue = trainData[responses.ravel()==1]plt.scatter(blue[:,0],blue[:,1],80,'b','s')newcomer = np.random.randint(0,100,(5,2)).astype(np.float32)plt.scatter(newcomer[:,0],newcomer[:,1],80,'g','o')knn = cv2.ml.KNearest_create()knn.train(trainData,cv2.ml.ROW_SAMPLE,responses)ret, results, neighbours, dist = knn.findNearest(newcomer, 3)print ("results: ", results,"\n")print ("neighbours: ", neighbours,"\n")print ("distances: ", dist)plt.show()
Here is the result which i got from it....