1. 程式人生 > >Python3 AttributeError: module 'cv2' has no attribute 'KNearest'

Python3 AttributeError: module 'cv2' has no attribute 'KNearest'

問題:在用python3使用knn = cv2.KNearest()的時候,可能會產生錯誤:AttributeError: module 'cv2' has no attribute 'KNearest'

newcomer = np.random.randint(0, 100, (1, 2)).astype(np.float32)
plt.scatter(newcomer[:, 0], newcomer[:, 1], 80, 'g', 'o')
knn = cv2.KNearest()

報錯資訊:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-21-f4d6e47beea6> in <module>()
      1 newcomer = np.random.randint(0, 100, (1, 2)).astype(np.float32)
      2 plt.scatter(newcomer[:, 0], newcomer[:, 1], 80, 'g', 'o')
----> 3 knn = cv2.KNearest()
      4 knn.train(trainData, responses)
      5 

AttributeError: module 'cv2' has no attribute 'KNearest'

解決:將knn = cv2.KNearest()替換為:

              knn = cv2.ml.KNearest_create()

變更樣例:

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()

 

說明:問題產生的環境
           Python版本:3.6.5
           OpenCV版本:3.4.2