python长度转换代码_类型错误:只能将长度为1的数组转换为Python标量

I am a beginner to openCV and am trying to analyse an existing code for a sudoku solver. There is this section of code which throws an error.

samples = np.float32(np.loadtxt('feature_vector_pixels.data'))

responses = np.float32(np.loadtxt('samples_pixels.data'))

model = cv2.ml.KNearest_create()

model.train(samples, responses)

The error is as follows Type Error: Only length-1 arrays can be converted to Python Scalars.

The complete traceback is as below:

C:\Study stuff\FinalProject>c:\Python27\python.exe Sudoku.py

Traceback (most recent call last):

File "Sudoku.py", line 15, in

model.train(samples, responses)

TypeError: only length-1 arrays can be converted to Python scalars

Any idea as to what the issue is?

解决方案

The error message that you are getting:

TypeError: Only length-1 arrays can be converted to Python Scalars

literally means: you have provided an array of more than one element in a place where a single value or an array of a single element was expected.

So one of the arguments passed to call model.train(samples, responses) requires and scalar... but which?

A look at the latest documentation of KNearest class, allow us to see the signature of the StatsModel.train method:

virtual bool cv::ml::StatModel::train ( InputArray samples, int layout, InputArray responses )

Apparently, a new layout argument was added. But it's meaning is a little obscure from the documentation.

Without knowledge of the contents of you file, I can't tell if you need to pass ROW_SAMPLE or COL_SAMPLE, but armed with that information, I could find a similar question, whose solution was to add cv2.ml.ROW_SAMPLE as second argument to the train method:

model.train(samples, cv2.ml.ROW_SAMPLE, responses)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值