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

猜你喜欢

转载自blog.csdn.net/zhangpan929/article/details/86217374