gpt4 book ai didi

python - opencv knn 类型错误 : only length-1 arrays can be converted to Python scalars

转载 作者:行者123 更新时间:2023-11-30 22:56:22 25 4
gpt4 key购买 nike

我正在尝试按照教程 http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_ml/py_knn/py_knn_opencv/py_knn_opencv.html 进行操作并将 KNearest 替换为 cv2.m1.KNearest_create() 但我收到 TypeError: only length-1 arrays can be conversion to Python scalars

import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('digits.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# Now we split the image to 5000 cells, each 20x20 size
cells = [np.hsplit(row,100) for row in np.vsplit(gray,50)]

# Make it into a Numpy array. It size will be (50,100,20,20)
x = np.array(cells)

# Now we prepare train_data and test_data.
train = x[:,:50].reshape(-1,400).astype(np.float32) # Size = (2500,400)
test = x[:,50:100].reshape(-1,400).astype(np.float32) # Size = (2500,400)

# Create labels for train and test data
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = train_labels.copy()

# Initiate kNN, train the data, then test it with test data for k=1
cv2.m1.KNearest_create()
knn.train(train,train_labels)
ret,result,neighbours,dist = knn.find_nearest(test,k=5)

# Now we check the accuracy of classification
# For that, compare the result with test_labels and check which are wrong
matches = result==test_labels
correct = np.count_nonzero(matches)
accuracy = correct*100.0/result.size
print accuracy

(我正在使用树莓派并按照本教程安装 open cv http://www.pyimagesearch.com/2015/10/26/how-to-install-opencv-3-on-raspbian-jessie/ 随后我 pip 安装了 matplotlib)

最佳答案

参数cv2.ml.ROW_SAMPLE丢失,将knn.find_nearest(test,k=5)修改为下面的代码。这是openCv3中的新功能,请引用openCv官网http://docs.opencv.org/3.0.0/dd/de1/classcv_1_1ml_1_1KNearest.html

    ` knn.train(train, cv2.ml.ROW_SAMPLE, train_labels)
ret, result, neighbours, dist = knn.findNearest(test, k=5)`

关于python - opencv knn 类型错误 : only length-1 arrays can be converted to Python scalars,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37034596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com