Harris特征计算两张图片相似度的代码
时间: 2023-05-22 10:03:21 浏览: 114
基于harris角点特征提取的图像拼接算法matlab仿真+仿真录像
5星 · 资源好评率100%
以下是基于OpenCV实现Harris特征计算,用于计算两张图片相似度的代码:
```
import cv2
# 读取两张待比较的图片
img1 = cv2.imread('image1.jpg', cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread('image2.jpg', cv2.IMREAD_GRAYSCALE)
# Harris特征检测器参数设置
block_size = 2
aperture_size = 3
k = 0.04
# 计算Harris角点
harris_img1 = cv2.cornerHarris(img1, block_size, aperture_size, k)
harris_img2 = cv2.cornerHarris(img2, block_size, aperture_size, k)
# 归一化Harris特征图像,方便后续操作
cv2.normalize(src=harris_img1, dst=harris_img1, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX)
cv2.normalize(src=harris_img2, dst=harris_img2, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX)
# 利用ORB算法检测特征点
orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)
# 利用FLANN算法进行特征点匹配
index_params = dict(algorithm=0, trees=5)
search_params = dict(checks=50)
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1, des2, k=2)
# 优化特征点匹配
good_points = []
for m, n in matches:
if m.distance < 0.7 * n.distance:
good_points.append(m)
# 计算两张图片相似度
similarity = len(good_points) / max(len(des1), len(des2))
print('图片相似度为:%.2f' % similarity)
# 可视化匹配结果(仅供参考)
img3 = cv2.drawMatches(img1, kp1, img2, kp2, good_points[:10], None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
cv2.imshow('matches', img3)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
注意:此代码仅为示例,可能需要根据实际需求进行修改。
阅读全文