Knearest() 函数在 opencv 2.4.8 和 python 2.7.5 中不起作用

Knearest() function Not Working in opencv 2.4.8 and python 2.7.5

我在 Ubuntu 14.04

中使用 OpenCV 2.4.8 和 python 2.7.5

当我打电话时

knn=cv2.KNearest()

我收到一条错误消息

knn=cv2.KNearest() AttributeError: 'module' object has no attribute 'KNearest'

我该如何解决? 完整代码在这里

 import cv2
 import numpy as np
 #######   training part    ############### 
 samples = np.loadtxt('generalsamples.data',np.float32)
 responses = np.loadtxt('generalresponses.data',np.float32)
 responses = responses.reshape((responses.size,1))

 model = cv2.KNearest()

 model.train(samples,responses)
#######################测试部分
im = cv2.imread('training_images/number1.jpg')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

image,contours,hierarchy =       cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists =            model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0) & 0 x FF

那是调用 KNearest() 的正确方法,所以你做错了什么。

这是一个完整的使用 k 最近邻的工作示例,取自 [此处]。

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

# 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.KNearest()
knn.train(trainData,responses)
ret, results, neighbours ,dist = knn.find_nearest(newcomer, 3)

print "result: ", results,"\n"
print "neighbours: ", neighbours,"\n"
print "distance: ", dist

plt.show()

如果这不起作用,那么你的问题就更大了。

我已经解决了这个问题。问题出在 opencv 版本中。这就是它无法识别 KNN 函数的原因。我已经安装了 opencv 2.4.10,它工作正常。谢谢大家