天天看點

2021年最新解決辦法之AttributeError: ‘module‘ object has no attribute ‘xfeatures2d‘

參考大型基佬交友網站:

https://stackoverflow.com/questions/37039224/attributeerror-module-object-has-no-attribute-xfeatures2d-python-opencv-2

解決辦法分為兩個部分:

1.重裝cv2(可能其他版本也能用,但是我沒有驗證過)

pip install opencv-python==4.5.1.48
pip install opencv-contrib-python==4.5.1.48
           

2.修改調用的函數

新版本的不再支援cv2.xfeatures2d.SIFT_create()進行調用

是以将:

修改為:

即可。

附上SIFT配準代碼,以填上一個坑:

import numpy as np
import cv2
import os

def get_good_match(des1,des2):
    bf = cv2.BFMatcher()
    matches = bf.knnMatch(des1, des2, k=2)
    good = []
    for m, n in matches:
        if m.distance < 0.75 * n.distance:
            good.append(m)
    return good

def sift_kp(image):
    gray_image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    sift = cv2.SIFT_create()
    kp,des = sift.detectAndCompute(image,None)
    kp_image = cv2.drawKeypoints(gray_image,kp,None)
    return kp_image,kp,des

def siftImageAlignment(img1,img2):
   _,kp1,des1 = sift_kp(img1)
   _,kp2,des2 = sift_kp(img2)
   goodMatch = get_good_match(des1,des2)
   if len(goodMatch) > 4:
       ptsA= np.float32([kp1[m.queryIdx].pt for m in goodMatch]).reshape(-1, 1, 2)
       ptsB = np.float32([kp2[m.trainIdx].pt for m in goodMatch]).reshape(-1, 1, 2)
       ransacReprojThreshold = 4
       H, status =cv2.findHomography(ptsA,ptsB,cv2.RANSAC,ransacReprojThreshold);
       imgOut = cv2.warpPerspective(img2, H, (img1.shape[1],img1.shape[0]),flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)
   return imgOut,H,status

if __name__=='__main__':
    img1 = cv2.imread("/../201909043_8d5ccdab501e6cf30201909041759495OK.jpg")
    img2 = cv2.imread("/../template_201909043.jpg")
    base_name = "_201909043.jpg"
    savepath = "/../"
    result,_,_ = siftImageAlignment(img1,img2)
    minus_image = img1-result
    cv2.imwrite(os.path.join(savepath, 'sift'+base_name), result)
    cv2.imwrite(os.path.join(savepath, 'minus'+base_name), minus_image)
           
2021年最新解決辦法之AttributeError: ‘module‘ object has no attribute ‘xfeatures2d‘