python opencv-3.0 SIFT/SURF 特征提取与匹配

版权声明:本文为博主原创文章,未经博主允许不得转载。Eddy_zheng https://blog.csdn.net/Eddy_zheng/article/details/78916009

一、环境准备

目前 Opencv 2.x 3.x 版本,两个版本之间的差异主要是一些功能函数被放置到了不同的功能模块,因此大多数情况两个版本的代码并不能通用。建议安装 Anaconda,自行下载相应版本。直接命令安装Opencv3, imagedt :

conda install -c menpo opencv3
pip install imagedt

二、SIFT/SURF 特征提取与匹配

# coding: utf-8
from matplotlib import pyplot as plt
from imagedt.decorator import time_cost
import cv2
print 'cv version: ', cv2.__version__


def bgr_rgb(img):
    (r, g, b) = cv2.split(img)
    return cv2.merge([b, g, r])


def orb_detect(image_a, image_b):
    # feature match
    orb = cv2.ORB_create()

    kp1, des1 = orb.detectAndCompute(image_a, None)
    kp2, des2 = orb.detectAndCompute(image_b, None)

    # create BFMatcher object
    bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

    # Match descriptors.
    matches = bf.match(des1, des2)

    # Sort them in the order of their distance.
    matches = sorted(matches, key=lambda x: x.distance)

    # Draw first 10 matches.
    img3 = cv2.drawMatches(image_a, kp1, image_b, kp2, matches[:100], None, flags=2)

    return bgr_rgb(img3)

@time_cost
def sift_detect(img1, img2, detector='surf'):
    if detector.startswith('si'):
        print "sift detector......"
        sift = cv2.xfeatures2d.SURF_create()
    else:
        print "surf detector......"
        sift = cv2.xfeatures2d.SURF_create()

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

    # BFMatcher with default params
    bf = cv2.BFMatcher()
    matches = bf.knnMatch(des1, des2, k=2)

    # Apply ratio test
    good = [[m] for m, n in matches if m.distance < 0.5 * n.distance]

    # cv2.drawMatchesKnn expects list of lists as matches.
    img3 = cv2.drawMatchesKnn(img1, kp1, img2, kp2, good, None, flags=2)

    return bgr_rgb(img3)


if __name__ == "__main__":
    # load image
    image_a = cv2.imread('./img1.jpg')
    image_b = cv2.imread('./img2.png')

    # ORB
    # img = orb_detect(image_a, image_b)

    # SIFT or SURF
    img = sift_detect(image_a, image_b)

    plt.imshow(img)
    plt.show()

三、输出展示

cv version:  3.1.0
surf detector......
==> time-cost: 0.187422     sift_detect

Output:
output

img1
这里写图片描述
img2
这里写图片描述

猜你喜欢

转载自blog.csdn.net/Eddy_zheng/article/details/78916009