python cv2 sift match

#coding=utf-8

import cv2
import numpy as np

print(cv2.__version__)#3.2.0
def visualize_matches(image1, keypoints1, image2, keypoints2, matches):
  m_image = np.array([])
  m_image = cv2.drawMatches(
      image1, keypoints1,
      image2, keypoints2,
      [match[0] for match in matches],
      m_image)
  cv2.imshow('PROJ_WIN', m_image)
  cv2.waitKey()

img = cv2.imread('img_write.tif', cv2.IMREAD_ANYCOLOR)
print(img.shape)
img_graycolor=cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
img_match = cv2.imread('test1.jpg', cv2.IMREAD_ANYCOLOR)
print(img_match.shape)
img_match_graycolor=cv2.cvtColor(img_match, cv2.COLOR_RGB2GRAY)

# detector_sift=cv2.xfeatures2d.SIFT_create()
# keypoints1=detector_sift.detect(img)
# keypoints2=detector_sift.detect(img_match)
# print(len(keypoints1))
descriptor_sift=cv2.xfeatures2d.SIFT_create()
# keypoints1, descriptors1 = descriptor_sift.compute(img_graycolor,keypoints1)
# keypoints2, descriptors2 = descriptor_sift.compute(img_match_graycolor,keypoints2)
keypoints1, descriptors1 = descriptor_sift.detectAndCompute(img_graycolor,None)
keypoints2, descriptors2 = descriptor_sift.detectAndCompute(img_match_graycolor,None)
print(len(keypoints1),len(descriptors1))
print(len(keypoints2),len(descriptors2))
# print(keypoints1)

matcher = cv2.BFMatcher()

matches = matcher.knnMatch(descriptors1, descriptors2, k=2)
matches = sorted(matches, key=lambda x: x[0].distance)

good = []
for m, n in matches:
    if m.distance < 0.7 * n.distance:
        good.append(m)
        # print(m)
print(len(good))
visualize_matches(img_graycolor, keypoints1, img_match_graycolor, keypoints2, matches[:100])

src_pts = np.float32([keypoints1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
dst_pts = np.float32([keypoints2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)

M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
matchesMask = mask.ravel().tolist()

h, w = img.shape[:2]
pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)
dst = cv2.perspectiveTransform(pts, M)
print(dst[0][0][0],dst[0][0][1],dst[2][0][0],dst[2][0][1])




# print(cv2.__version__)#2.4.9
# img = cv2.imread('test1.jpg', cv2.IMREAD_ANYCOLOR)
# print(img.shape)
# img_graycolor=cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# min_hessian = 400
# SURF = cv2.SURF(min_hessian)
# key_query, desc_query = SURF.detectAndCompute(img_graycolor, None)
#
# img_match = cv2.imread('img_write.tif', cv2.IMREAD_ANYCOLOR)
# print(img_match.shape)
# img_match_graycolor=cv2.cvtColor(img_match, cv2.COLOR_RGB2GRAY)
# # min_hessian = 400
# # SURF = cv2.SURF(min_hessian)
# key_query_match, desc_query_match = SURF.detectAndCompute(img_match_graycolor, None)
#
#
# imgOut = cv2.drawKeypoints(img_graycolor, key_query, None, (255, 0, 0), 4)
# # cv2.imshow('imgOut', imgOut)
# # cv2.waitKey()
#
# FLANN_INDEX_KDTREE = 0
# index_params = dict(algorithm = FLANN_INDEX_KDTREE,trees = 5)
# search_params = dict(checks=50)
# flann = cv2.FlannBasedMatcher(index_params,search_params)
# matches = flann.knnMatch(desc_query, desc_query_match, k=2)
# # print(matches)
# # discard bad matches, ratio test as per Lowe's paper
# good_matches = filter(lambda x: x[0].distance<0.7*x[1].distance, matches)
# print(len(good_matches))
# def draw_good_matches(img1, kp1, img2, kp2, matches):
#     # Create a new output image that concatenates the
#     # two images together (a.k.a) a montage
#     rows1, cols1 = img1.shape[:2]
#     rows2, cols2 = img2.shape[:2]
#     out = np.zeros((max([rows1, rows2]), cols1+cols2, 3), dtype='uint8')
#     # Place the first image to the left, copy 3x for RGB
#     out[:rows1, :cols1, :] = np.dstack([img1, img1, img1])
#     # Place the next image to the right of it, copy 3x for RGB
#     out[:rows2, cols1:cols1 + cols2, :] = np.dstack([img2, img2, img2])
#     for m in matches:
#         # Get the matching keypoints for each of the images
#         print(m)
#         # c1, r1 = kp1[m[0]].pt
#         # c2, r2 = kp2[m[1]].pt
#         c1, r1 = kp1[m.trainIdx].pt
#         c2, r2 = kp2[m.queryIdx].pt
#     radius = 4
#     BLUE = (255, 0, 0)
#     thickness = 1
#     # Draw a small circle at both co-ordinates
#     cv2.circle(out, (int(c1), int(r1)), radius, BLUE, thickness)
#     cv2.circle(out, (int(c2) + cols1, int(r2)), radius, BLUE, thickness)
#     # Draw a line in between the two points
#     cv2.line(out, (int(c1), int(r1)), (int(c2) + cols1, int(r2)), BLUE, thickness)
#     return out
# cv2.imshow('imgFlann', draw_good_matches(img_graycolor, key_query,
#                                          img_match_graycolor, key_query_match, good_matches))
使用aircv中的`match_template`函数可以进行SIFT特征点匹配。具体步骤如下: 1. 使用`SIFT`函数提取模板图和待匹配图的SIFT特征点和描述符。 ```python import cv2 import numpy as np import aircv as ac # 读取模板图和待匹配图 template_img = cv2.imread('template.png', 0) match_img = cv2.imread('match.png', 0) # 初始化SIFT对象 sift = cv2.xfeatures2d.SIFT_create() # 提取模板图和待匹配图的SIFT特征点和描述符 kp1, des1 = sift.detectAndCompute(template_img, None) kp2, des2 = sift.detectAndCompute(match_img, None) ``` 2. 使用`BFMatcher`函数进行特征点匹配。 ```python # 使用Brute-Force匹配器进行特征点匹配 bf = cv2.BFMatcher() matches = bf.knnMatch(des1, des2, k=2) ``` 3. 使用比值测试(Ratio Test)方法对匹配点进行筛选。 ```python # 比值测试 good = [] for m, n in matches: if m.distance < 0.7 * n.distance: good.append([m]) ``` 4. 使用`drawMatchesKnn`函数绘制匹配结果。 ```python # 绘制匹配结果 img3 = cv2.drawMatchesKnn(template_img, kp1, match_img, kp2, good, None, flags=2) cv2.imshow('match result', img3) cv2.waitKey(0) cv2.destroyAllWindows() ``` 完整代码如下: ```python import cv2 import numpy as np import aircv as ac # 读取模板图和待匹配图 template_img = cv2.imread('template.png', 0) match_img = cv2.imread('match.png', 0) # 初始化SIFT对象 sift = cv2.xfeatures2d.SIFT_create() # 提取模板图和待匹配图的SIFT特征点和描述符 kp1, des1 = sift.detectAndCompute(template_img, None) kp2, des2 = sift.detectAndCompute(match_img, None) # 使用Brute-Force匹配器进行特征点匹配 bf = cv2.BFMatcher() matches = bf.knnMatch(des1, des2, k=2) # 比值测试 good = [] for m, n in matches: if m.distance < 0.7 * n.distance: good.append([m]) # 绘制匹配结果 img3 = cv2.drawMatchesKnn(template_img, kp1, match_img, kp2, good, None, flags=2) cv2.imshow('match result', img3) cv2.waitKey(0) cv2.destroyAllWindows() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值