git:https://github.com/linyi0604/Computer-Vision
bf暴力匹配:
1 # coding:utf-8
2
3 import cv2
4
5 """
6 orb特征检测和匹配
7 两幅图片分别是 乐队的logo 和包含该logo的专辑封面
8 利用orb进行检测后进行匹配两幅图片中的logo
9
10 """
11 # 按照灰度图像的方式读入两幅图片
12 img1 = cv2.imread("../data/logo1.png", cv2.IMREAD_GRAYSCALE)
13 img2 = cv2.imread("../data/album1.png", cv2.IMREAD_GRAYSCALE)
14
15 # 创建ORB特征检测器和描述符
16 orb = cv2.ORB_create()
17 # 对两幅图像检测特征和描述符
18 keypoint1, descriptor1 = orb.detectAndCompute(img1, None)
19 keypoint2, descriptor2 = orb.detectAndCompute(img2, None)
20 """
21 keypoint 是一个包含若干点的列表
22 descriptor 对应每个点的描述符 是一个列表, 每一项都是检测到的特征的局部图像
23
24 检测的结果是关键点
25 计算的结果是描述符
26
27 可以根据监测点的描述符 来比较检测点的相似之处
28
29 """
30 # 获得一个暴力匹配器的对象
31 bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
32 # 利用匹配器 匹配两个描述符的相近成都
33 maches = bf.match(descriptor1, descriptor2)
34 # 按照相近程度 进行排序
35 maches = sorted(maches, key=lambda x: x.distance)
36 # 画出匹配项
37 img3 = cv2.drawMatches(img1, keypoint1, img2, keypoint2, maches[: 30], img2, flags=2)
38
39 cv2.imshow("matches", img3)
40 cv2.waitKey()
41 cv2.destroyAllWindows()
knn匹配:
1 # coding:utf-8
2
3 import cv2
4
5 # 按照灰度图像读入两张图片
6 img1 = cv2.imread("../data/logo1.png", cv2.IMREAD_GRAYSCALE)
7 img2 = cv2.imread("../data/album1.png", cv2.IMREAD_GRAYSCALE)
8
9 # 获取特征提取器对象
10 orb = cv2.ORB_create()
11 # 检测关键点和特征描述
12 keypoint1, desc1 = orb.detectAndCompute(img1, None)
13 keypoint2, desc2 = orb.detectAndCompute(img2, None)
14 """
15 keypoint 是关键点的列表
16 desc 检测到的特征的局部图的列表
17 """
18 # 获得knn检测器
19 bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
20 matches = bf.knnMatch(desc1, desc2, k=1)
21 """
22 knn 匹配可以返回k个最佳的匹配项
23 bf返回所有的匹配项
24 """
25 # 画出匹配结果
26 img3 = cv2.drawMatchesKnn(img1, keypoint1, img2, keypoint2, matches, img2, flags=2)
27 cv2.imshow("matches", img3)
28 cv2.waitKey()
29 cv2.destroyAllWindows()
FLANN匹配:
# coding:utf-8
import cv2
"""
FLANN是类似最近邻的快速匹配库
它会根据数据本身选择最合适的算法来处理数据
比其他搜索算法快10倍
"""
# 按照灰度图片读入
img1 = cv2.imread("../data/logo1.png", cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread("../data/album1.png", cv2.IMREAD_GRAYSCALE)
# 创建sift检测器
sift = cv2.xfeatures2d.SIFT_create()
# 查找监测点和匹配符
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)
"""
keypoint是检测到的特征点的列表
descriptor是检测到特征的局部图像的列表
"""
# 获取flann匹配器
FLANN_INDEX_KDTREE = 0
indexParams = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
searchParams = dict(checks=50)
flann = cv2.FlannBasedMatcher(indexParams, searchParams)
# 进行匹配
matches = flann.knnMatch(des1, des2, k=2)
# 准备空的掩膜 画好的匹配项
matchesMask = [[0, 0] for i in range(len(matches))]
for i, (m, n) in enumerate(matches):
if m.distance < 0.7*n.distance:
matchesMask[i] = [1, 0]
drawPrams = dict(matchColor=(0, 255, 0),
singlePointColor=(255, 0, 0),
matchesMask=matchesMask,
flags=0)
# 匹配结果图片
img3 = cv2.drawMatchesKnn(img1, kp1, img2, kp2, matches, None, **drawPrams)
cv2.imshow("matches", img3)
cv2.waitKey()
cv2.destroyAllWindows()