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=cv2.xfeatures2d.SIFT_create()

修改为:

sift=cv2.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‘_第1张图片

你可能感兴趣的:(问题记录,中级,python,sift算法)