参考 https://blog.csdn.net/yuxuan_08/article/details/87966840
在用python3使用sift = cv2.SIFT()进行SIFT时候,可能会产生错误:AttributeError: module ‘cv2’ has no attribute ‘SIFT’
import numpy as np
import cv2
from matplotlib import pyplot as plt
MIN_MATCH_COUNT = 10
img1 = cv2.imread('red_cube.jpg', 0) # queryImage
img2 = cv2.imread('image_106.jpg', 0) # trainImage
# Initiate SIFT detector
sift = cv2.SIFT()
# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)
运行会报错
/home/li/anaconda3/bin/python /home/li/opencv/opencv-python/match01.py
Traceback (most recent call last):
File "/home/li/opencv/opencv-python/match01.py", line 13, in
sift = cv2.SIFT()
AttributeError: module 'cv2.cv2' has no attribute 'SIFT'
解决:将sift = cv2.SIFT()替换为:sift = cv2.xfeatures2d.SIFT_create()
分析:opencv将SIFT等算法整合到xfeatures2d集合里面了。写法:sift = cv2.xfeatures2d.SIFT_create()
import numpy as np
import cv2
from matplotlib import pyplot as plt
MIN_MATCH_COUNT = 10
img1 = cv2.imread('red_cube.jpg', 0) # queryImage
img2 = cv2.imread('image_106.jpg', 0) # trainImage
# Initiate SIFT detector
# sift = cv2.SIFT() 将sift = cv2.SIFT()替换为:sift = cv2.xfeatures2d.SIFT_create()
sift = cv2.xfeatures2d.SIFT_create()
# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)
然后还有报错,AttributeError: module ‘cv2.cv2’ has no attribute ‘xfeatures2d’
/home/li/anaconda3/bin/python /home/li/opencv/opencv-python/match01.py
Traceback (most recent call last):
File "/home/li/opencv/opencv-python/match01.py", line 13, in
sift = cv2.xfeatures2d.SIFT_create()
AttributeError: module 'cv2.cv2' has no attribute 'xfeatures2d'
这个方法的博主opencv是3.X,而我的是4.X,所以还要修改,
继续参考 https://blog.csdn.net/github_38236333/article/details/78781210?depth_1-utm_source=distribute.pc_relevant_right.none-task&utm_source=distribute.pc_relevant_right.none-task
原因:3.X以后OpenCv只包含部分内容,需要神经网络或者其他的函数需要导入opencv_contrib
解决 pip install opencv-contrib-python
如果已经安装OpenCv2,则需要先卸载pip uninstall opencv-python再安装
参考 https://pypi.org/project/opencv-contrib-python/
我安装完之后还是有问题,
/home/li/anaconda3/bin/python /home/li/opencv/opencv-python/match01.py
Traceback (most recent call last):
File "/home/li/opencv/opencv-python/match01.py", line 19, in
sift = cv2.xfeatures2d.SIFT_create()
cv2.error: OpenCV(4.2.0) /io/opencv_contrib/modules/xfeatures2d/src/sift.cpp:1210: error: (-213:The function/feature is not implemented) This algorithm is patented and is excluded in this configuration; Set OPENCV_ENABLE_NONFREE CMake option and rebuild the library in function 'create'
好像是sift有专利权,
将opencv版本退到3.4.2即可解决,卸载之前的包,然后
pip install opencv-python ==3.4.2.17
pip install opencv-contrib-python == 3.4.2.17
亲测有效!