2.1 Harris角点检测器的原理
import cv2
import numpy as np
# 读取图像
img = cv2.imread('1.jpg')
# 转为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 计算Harris角点响应函数
dst = cv2.cornerHarris(gray, 2, 3, 0.04)
# 阈值化响应函数,得到角点
threshold = 0.01 * dst.max()
corners = np.where(dst > threshold)
# 绘制角点
for i in range(len(corners[0])):
x, y = corners[1][i], corners[0][i]
cv2.circle(img, (x, y), 5, (0, 0, 255), -1)
# 显示图像
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
2.2 SIFT(尺度不变特征变换)
import cv2
# 读取图像
img = cv2.imread('1.jpg')
# 创建SIFT对象
sift = cv2.xfeatures2d.SIFT_create()
# 检测图像中的关键点
keypoints = sift.detect(img, None)
# 提取关键点的SIFT特征向量
keypoints, descriptors = sift.compute(img, keypoints)
# 可视化关键点
img = cv2.drawKeypoints(img, keypoints, None)
# 显示图像
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
2.3 SIFT匹配描述子
10个点
import cv2
# 读取图像1和图像2
img1 = cv2.imread('1.jpg')
img1 = cv2.resize(img1, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
img2 = cv2.imread('2.jpg')
img2 = cv2.resize(img2, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
# 创建SIFT对象
sift = cv2.xfeatures2d.SIFT_create()
# 检测图像1和图像2中的关键点
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)
# 创建暴力匹配器
bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)
# 匹配图像1和图像2中的特征点
matches = bf.match(des1, des2)
# 根据距离排序,保留前10个匹配点
matches = sorted(matches, key=lambda x: x.distance)[:10]
# 可视化匹配结果
img3 = cv2.drawMatches(img1, kp1, img2, kp2, matches, None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
# 显示图像
cv2.imshow('Image', img3)
cv2.waitKey(0)
cv2.destroyAllWindows()
1000个点
import cv2
# 读取图像1和图像2
img1 = cv2.imread('example1.jpg')
img2 = cv2.imread('example2.jpg')
# 创建SIFT对象
sift = cv2.xfeatures2d.SIFT_create()
# 检测图像1和图像2中的关键点
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)
# 创建暴力匹配器
bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)
# 匹配图像1和图像2中的特征点
matches = bf.match(des1, des2)
# 根据距离排序,保留前10个匹配点
matches = sorted(matches, key=lambda x: x.distance)[:10]
# 可视化匹配结果
img3 = cv2.drawMatches(img1, kp1, img2, kp2, matches, None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
# 显示图像
cv2.imshow('Image', img3)
cv2.waitKey(0)
cv2.destroyAllWindows()