首页 > 编程语言 > 详细

only size-1 arrays can be converted to Python scalars

时间:2018-09-29 14:01:06      阅读:6151      评论:0      收藏:0      [点我收藏+]

标签:con   ray   nbsp   res   with   trac   recent   ini   put   

python版本:3.6.5

opencv版本:3.2.0

使用的jupyter notebook

源码如下:

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()

错误如下:

---------------------------------------------------------------------------
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

错误原因:

传递的参数错误

train函数中第二个参数应该是数组的布局方式

应该根据传入数组的形式填cv2.ml.ROW_SAMPLE或者cv2.ml.COL_SAMPLE

例如我的就是

knn.train(trainData,cv2.ml.ROW_SAMPLE,responses)

参考地址:https://stackoverflow.com/questions/33975695/type-error-only-length-1-arrays-can-be-converted-to-python-scalars

 

only size-1 arrays can be converted to Python scalars

标签:con   ray   nbsp   res   with   trac   recent   ini   put   

原文:https://www.cnblogs.com/Summerio/p/9723099.html

(1)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 bubuko.com 版权所有 鲁ICP备09046678号-4
打开技术之扣,分享程序人生!
             

鲁公网安备 37021202000002号