python+opencv特征匹配算法

python+opencv特征匹配算法

1.安装

pip install opencv-python
pip install numpy

2.算法明细

import cv2
import numpy as np

# 读取两张图像
img1 = cv2.imread('image1.jpg',0)  # queryImage
img2 = cv2.imread('image2.jpg',0)  # trainImage

# 初始化SIFT对象
sift = cv2.xfeatures2d.SIFT_create()

# 计算两个图像的SIFT特征和描述符
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)

# 使用FLANN匹配器进行特征匹配
FLANN_INDEX_KDTREE = 1
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks=50)
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1,des2,k=2)

# 根据Lowe的比率测试进行匹配
good_matches = []
for m,n in matches:
    if m.distance < 0.7*n.distance:
        good_matches.append(m)

# 计算并输出相似度
similarity = len(good_matches)/len(matches)
print('相似度: ', similarity)

# 输出匹配结果
img3 = cv2.drawMatches(img1,kp1,img2,kp2,good_matches,None,flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)

# 显示匹配结果
cv2.imshow('Matches', img3)
cv2.waitKey(0)
cv2.destroyAllWindows()

3.报错处理

AttributeError: module 'cv2' has no attribute 'xfeatures2d'

由于该算法已被申请专利,只能使用低版本

pip install opencv-python==3.4.2.16
pip install opencv-contrib-python==3.4.2.16

你可能感兴趣的:(opencv,opencv,python,算法)