首先安装contrib
,并检查和opencv-python
版本是否一致
pip install opencv-contrib-python
pip list
但是依然报错
sift = cv2.xfeatures2d.SIFT_create()
# 报错信息
AttributeError: module 'cv2.cv2' has no attribute 'xfeatures2d'
首先卸载当前版本
pip uninstall opencv-python
pip uninstall opencv-contrib-python
然后重新安装
pip install opencv-python==3.4.2.16
pip install opencv-contrib-python==3.4.2.16
如果还是不行,重启一下anaconda,问题解决。
核心公式
# 新建一个sift算子
sift = cv2.xfeatures2d.SIFT_create()
# 计算特征点和特征点周围的特征向量
kp1, des1 = sift.detectAndCompute(img1,None)
# 进行KNN特征匹配,k设置为2
matches = cv2.BFMatcher().knnMatch(des1,des2, k=2)
# 进行匹配点筛选,这个地方一直没看懂
for m,n in matches:
if m.distance < 0.75*n.distance:
good.append([m])
# 在匹配的点之间进行连线
imgNew = cv2.drawMatchesKnn(img1,kp1,img2,kp2,good,None,flags=2)
完整代码
import numpy as np
import cv2
import matplotlib.pyplot as plt
print("debug")
# 加载图片
img1 = cv2.imread('images/1.jpg',0) # queryImage
# img3是和img1一样的照片
img3 = cv2.imread('images/3.jpg',0)
# 对这张照片进行高斯模糊
blurred = cv2.GaussianBlur(img3, (9, 9), 0)
# 再旋转
(height, width) = blurred.shape[:2]
center = (width//2, height//2)
# 定义旋转矩阵,3个参数分别为:旋转中心,旋转角度,缩放比率
M = cv2.getRotationMatrix2D(center, 45, 1.0)
# 正式旋转,这样就得到了和原始图片img1不太一样的照片
rotated = cv2.warpAffine(blurred, M, (width,height))
img2 = rotated
cv2.imshow("original image",img1)
cv2.waitKey(0)
cv2.imshow("after blurred and rotated",img2)
cv2.waitKey(0)
# 初始化SIFT算子,如果不能用,使用pip安装如下版本的库并重启conda
# pip install opencv-python == 3.4.2.16
# pip install opencv-contrib-python == 3.4.2.16
sift = cv2.xfeatures2d.SIFT_create()
# 使用SIFT算子计算特征点和特征点周围的特征向量
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)
# BFMatcher中设置knn的k值
bf = cv2.BFMatcher()
matches = bf.knnMatch(des1,des2, k=2)
# Apply ratio test
good = []
for m,n in matches:
if m.distance < 0.75*n.distance:
good.append([m])
# cv.drawMatchesKnn expects list of lists as matches.
imgNew = cv2.drawMatchesKnn(img1,kp1,img2,kp2,good,None,flags=2)
# 保存图片
cv2.imwrite("imgNew.jpg",imgNew)
# 使用plt绘制
plt.imshow(imgNew),plt.show()
cv2.destroyAllWindows()
运行结果
原图:
模糊和旋转之后
进行特征点匹配