1. 程式人生 > >python3 TypeError: Incorrect type of self (must be 'Feature2D' or its derivative)

python3 TypeError: Incorrect type of self (must be 'Feature2D' or its derivative)

問題:在用python3使用orb = cv2.ORB()進行ORB時候,可能會產生錯誤:TypeError: Incorrect type of self (must be 'Feature2D' or its derivative)

import numpy as np
import cv2
from matplotlib import pyplot as plt
img1 = cv2.imread('data/queryImage.jpg', 0)  # queryImage
img2 = cv2.imread('data/trainImage.jpg', 0)  # trainImage
# Initiate SIFT detector
orb = cv2.ORB()
# find the keypoints and descriptors with SIFT
kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)

報錯資訊:

TypeError                                 Traceback (most recent call last)
<ipython-input-42-dfae86b275b4> in <module>()
      3 
      4 # find the keypoints and descriptors with ORB
----> 5 kp1, des1 = orb.detectAndCompute(img1,None)
      6 kp2, des2 = orb.detectAndCompute(img2,None)
      7 

TypeError: Incorrect type of self (must be 'Feature2D' or its derivative)

解決:將orb = cv2.ORB()替換為:orb = cv2.ORB_create()

分析:

        在opencv2中, orb = cv2.ORB ()是對的;
        在opencv3中這樣會報錯,改成orb = cv2.ORB_create()就沒問題了。

變更樣例:

import numpy as np
import cv2
from matplotlib import pyplot as plt
img1 = cv2.imread('data/queryImage.jpg', 0)  # queryImage
img2 = cv2.imread('data/trainImage.jpg', 0)  # trainImage
# Initiate SIFT detector
#orb = cv2.ORB()  將orb= cv2.ORB()替換為:orb= cv2.ORB_create()
orb= cv2.ORB_create()
# find the keypoints and descriptors with SIFT
kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)

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