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

问题:在用python3使用knn.train(trainData, responses)的时候,可能会产生错误:TypeError: only size-1 arrays can be converted to Python scalars

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)

报错信息:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-3bcbba22ba1e> in <module>()
      2 plt.scatter(newcomer[:, 0], newcomer[:, 1], 80, 'g', 'o')
      3 knn = cv2.ml.KNearest_create()
----> 4 knn.train(trainData, responses)
      5 

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

解决:将knn.train(trainData, responses)替换为:

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

分析:

        在python3中,knn.train需要传入layout参数,如第二种构造方法

Docstring:
train(trainData[, flags]) -> retval
.   @brief Trains the statistical model
.   
.   @param trainData training data that can be loaded from file using TrainData::loadFromCSV or
.   created with TrainData::create.
.   @param flags optional flags, depending on the model. Some of the models can be updated with the
.   new training samples, not completely overwritten (such as NormalBayesClassifier or ANN_MLP).


train(samples, layout, responses) -> retval
.   @brief Trains the statistical model
.   
.   @param samples training samples
.   @param layout See ml::SampleTypes.
.   @param responses vector of responses associated with the training samples.
Type:      builtin_function_or_method

变更样例:

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

参考文章:http://www.itkeyword.com/doc/6947006191723413×615/knn-train-in-cv2-with-opencv-3-0

说明:问题产生的环境
           Python版本:3.6.5
           OpenCV版本:3.4.2

转自:https://blog.csdn.net/yuxuan_08/article/details/87966958

    原文作者:zhangpan929
    原文地址: https://blog.csdn.net/zhangpan929/article/details/86217126
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞