Python version: 3.6.5
Opencv version: 3.2.0
Jupyter notebook used
The source code is as follows:
import cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# 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')
knn = cv2.ml.KNearest_create()
knn.train(trainData,responses)
ret, results, neighbours ,dist = knn.findNearest(newcomer, 3)
print ("result: ", results,"\n")
print ("neighbours: ", neighbours,"\n")
print ("distance: ", dist)
plt.show()
The error is as follows:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-21-b1c5cdca5e57> in <module>()
20 knn = cv2.ml.KNearest_create()
21
---> 22 knn.train(trainData,responses)
23 ret, results, neighbours ,dist = knn.findNearest(newcomer, 3)
24
TypeError: only size-1 arrays can be converted to Python scalars
Error reason:
Wrong parameter passed
The second parameter in the train function should be the layout of the array
Cv2.ml.row should be filled in according to the form of the passed in array_ Sample or cv2.ml.col_ SAMPLE
For example, mine is
knn.train(trainData,cv2.ml.ROW_SAMPLEļ¼responses)
Similar Posts:
- Preservation and recovery of TF. Train. Saver () model of tensorflow
- Tensorflowcenter {typeerror} non hashable type: “numpy. Ndarray”
- Python3 urlopen() TypeError: can’t convert ‘bytes’ object to str im…
- Python TypeError: ‘numpy.float64’ object cannot be interpreted as an index
- InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor ‘…
- Pycharm introduces numpy error: ImportError: Importing the multiarray numpy extension module failed. Most likely you are trying to import a failed build of numpy.
- How to Solve Libpng warning ICCP error
- [Solved] Pycharm Error: Error: failed to send plot to http://127.0.0.1:63342
- The Usage of Numpy.unravel_index() function
- Tensorflow error due to uninitialized variable [How to Fix]