我读了 SOF 页面Simple Digit Recognition OCR in OpenCV-Python
然后我尝试自己运行以下代码:
import cv2
import numpy as np
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))
print "samples: \n",samples
print "respnses: \n",responses
model = cv2.ml.KNearest_create()
model.train(samples,cv2.ml.ROW_SAMPLE,responses)
输出:
samples:
[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 65. 0. 0. 0. 0. 0.
0. 0. 1. 65. 0. 0. 0. 0. 0. 0. 0. 1. 49. 16. 0.
0. 0. 0. 0. 0. 1. 1. 65. 0. 0. 0. 0. 0. 0. 1.
1. 65. 0. 0. 0. 0. 0. 0. 0. 1. 65. 0. 0. 0. 0.
0. 0. 0. 1. 65. 0. 0. 0. 0. 0. 0. 0. 1. 65. 0.
0. 0. 0. 0. 0. 0. 1. 11. 55. 0. 0. 0. 0. 0. 0.
1. 4. 62. 0. 0. 0. 0. 0. 0. 0.]
respnses:
[[ 7.]]
错误:
Traceback (most recent call last):
File "test.py", line 10, in <module>
model.train(samples,cv2.ml.ROW_SAMPLE,responses)
cv2.error: OpenCV(4.0.0-pre) /home/shajal/opencv/opencv/modules/ml/src/data.cpp:259: error: (-215:Assertion failed) samples.type() == 5 || samples.type() == 4 in function 'setData'
我该怎么办?
我已经在我的Ubuntu机器上重新安装了Opencv来解决这个问题。
答案 0 :(得分:1)
使用 model.train(samples,cv2.ml.ROW_SAMPLE,响应)时,请检查以下内容:
答案 1 :(得分:0)
我使用OpenCV 3.4.0.12和Python 3.6得到了这个错误。
OpenCV Error: Assertion failed ((layout == ROW_SAMPLE && responses.rows == nsamples) || (layout == COL_SAMPLE && responses.cols == nsamples)) in setData, file /io/opencv/modules/ml/src/data.cpp, line 298
Traceback (most recent call last):
File "test.py", line 13, in <module>
model.train(samples,cv2.ml.ROW_SAMPLE,responses)
cv2.error: /io/opencv/modules/ml/src/data.cpp:298: error: (-215) (layout == ROW_SAMPLE && responses.rows == nsamples) || (layout == COL_SAMPLE && responses.cols == nsamples) in function setData
所以我认为你的尺寸必须有错误
(layout == ROW_SAMPLE && responses.rows == nsamples) || (layout == COL_SAMPLE && responses.cols == nsamples)
说。
编辑:
是的,问题是维度,在思考了一下并理解了这一点后,我终于意识到发生了什么,更容易解决。
你做
responses = responses.reshape((responses.size,1))
因为响应被读取为float而不是数组。在完成[[ 7. ]]
之后,您将获得reshape
。如果您查看样本数组,您会看到它是[ numbers ]
数组,而不是[[ numbers ]]
数组。
对样本做同样的事情会使一切正常。 因此,在创建样本后添加:samples = samples.reshape((1, samples.size))
答案 2 :(得分:0)
这解决了我的问题:
在samples = np.loadtxt('generalsamples.data',np.float32)
使用samples = np.array(samples).astype('float32')
将numpy数组类型转换为float32