SITF 特征匹配 代码

#coding=utf-8
import cv2
import scipy as sp

img1 = cv2.imread('0.jpg',0) # queryImage
img2 = cv2.imread('1.jpg',0) # trainImage

# Initiate SIFT detector
sift = cv2.xfeatures2d.SIFT_create()

# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)

# FLANN parameters
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks=50)   # or pass empty dictionary
flann = cv2.FlannBasedMatcher(index_params,search_params)
matches = flann.knnMatch(des1,des2,k=2)

print 'matches...',len(matches)
# Apply ratio test
good = []
for m,n in matches:
    if m.distance < 0.75*n.distance:
        good.append(m)
print 'good',len(good)
# #####################################
# visualization
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
view = sp.zeros((max(h1, h2), w1 + w2, 3), sp.uint8)
view[:h1, :w1, 0] = img1
view[:h2, w1:, 0] = img2
view[:, :, 1] = view[:, :, 0]
view[:, :, 2] = view[:, :, 0]

for m in good:
    # draw the keypoints
    # print m.queryIdx, m.trainIdx, m.distance
    color = tuple([sp.random.randint(0, 255) for _ in xrange(3)])
    #print 'kp1,kp2',kp1,kp2
    cv2.line(view, (int(kp1[m.queryIdx].pt[0]), int(kp1[m.queryIdx].pt[1])) , (int(kp2[m.trainIdx].pt[0] + w1), int(kp2[m.trainIdx].pt[1])), color)

cv2.imshow("view", view)
cv2.waitKey()

 

第九行本来应是 sift = cv2.SIFT()

但会报错,没有SITF模块,原因:opencv将SIFT等算法整合到xfeatures2d集合里面了。变更后写法为:

sift = cv2.xfeatures2d.SIFT_create()

然后又出现错误:

Traceback (most recent call last):
  File "..\image\test.py", line 9, in <module>
    sift = cv2.xfeatures2d.SIFT_create()
AttributeError: module 'cv2' has no attribute 'xfeatures2d'

原因:**3.X以后OpenCv只包含部分内容,需要神经网络或者其他的函数需要导入opencv_contrib

注意:

导入时应标明版本,最新版本也无SIFT

否则报错

cv2.error: OpenCV(3.4.3) C:\projects\opencv-python\opencv_contrib\modules\xfeatures2d\src\sift.cpp:1207: <br>error: (-213:The function/feature is not implemented) This algorithm is patented and is excluded in this configuration; <br>Set OPENCV_ENABLE_NONFREE CMake option and rebuild the library in function 'cv::xfeatures2d::SIFT::create'

正确:::

sudo pip install --user opencv-contrib-python==3.3.0.10

python3版本把 pip 改为 pip3就行.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值