KNN train() in cv2 with opencv 3.0

Brad Foley picture Brad Foley · Oct 7, 2015 · Viewed 15k times · Source

I'm trying to run k-nearest neighbours using cv2 (python 2.7) and opencv 3.0. I've replicated the same error message using code like http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_ml/py_knn/py_knn_understanding/py_knn_understanding.html:

import cv2
import numpy as np
import matplotlib.pyplot as plt
# Feature set containing (x,y) values of 25 known/training data
trainData = np.random.randint(0,100,(25,2)).astype(np.float32)
# Labels each one either Red or Blue with numbers 0 and 1
responses = np.random.randint(0,2,(25,1)).astype(np.float32)
# Take Red families and plot them
red = trainData[responses.ravel()==0]
plt.scatter(red[:,0],red[:,1],80,'r','^')
# Take Blue families and plot them
blue = trainData[responses.ravel()==1]
plt.scatter(blue[:,0],blue[:,1],80,'b','s')
plt.show()
newcomer = np.random.randint(0,100,(1,2)).astype(np.float32)
plt.scatter(newcomer[:,0],newcomer[:,1],80,'g','o')

#The following line is modified for OpenCV 3.0
knn = cv2.ml.KNearest_create()
knn.train(trainData,responses)
ret, results, neighbours ,dist = knn.find_nearest(newcomer, 3)

print "result: ", results,"\n"
print "neighbours: ", neighbours,"\n"
print "distance: ", dist

plt.show()

I modified the line knn = cv2.ml.KNearest_create() for OpenCV 3, but the subsequent line produces an error "TypeError: only length-1 arrays can be converted to Python scalars" and I can't figure out what I should be using for the train function.

Answer

AdityaIntwala picture AdityaIntwala · Oct 7, 2015

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 cv2
import numpy as np
import matplotlib.pyplot as plt

trainData = 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....

KNN Output