OpenCV ORB 特征点检测与匹配 - Python 代码示例
OpenCV ORB 特征点检测与匹配 - Python 代码示例
本示例展示如何使用 OpenCV 的 ORB 算法检测图像中的特征点,并使用 BFMatcher 进行特征点匹配,以识别图像之间的相似性。
1. 读取图像
import cv2
# 读取图像
img1 = cv2.imread('1.png')
img2 = cv2.imread('2.png')
img3 = cv2.imread('3.png')
img4 = cv2.imread('4.png')
2. 创建 ORB 对象
# 创建 ORB 对象
orb = cv2.ORB_create()
3. 检测特征点
# 检测特征点
keypoints1 = orb.detect(img1, None)
keypoints2 = orb.detect(img2, None)
keypoints3 = orb.detect(img3, None)
keypoints4 = orb.detect(img4, None)
# 绘制特征点
img_with_keypoints1 = cv2.drawKeypoints(img1, keypoints1, None)
img_with_keypoints2 = cv2.drawKeypoints(img2, keypoints2, None)
img_with_keypoints3 = cv2.drawKeypoints(img3, keypoints3, None)
img_with_keypoints4 = cv2.drawKeypoints(img4, keypoints4, None)
cv2.imshow('ORB keypoints1', img_with_keypoints1)
cv2.imshow('ORB keypoints2', img_with_keypoints2)
cv2.imshow('ORB keypoints3', img_with_keypoints3)
cv2.imshow('ORB keypoints4', img_with_keypoints4)
cv2.waitKey(0)
4. 特征点匹配
要匹配这四张图像的特征点,可以使用 OpenCV 中的 BFMatcher(暴力匹配器)或 FLANNMatcher(快速最近邻匹配器)。
以下是使用 BFMatcher 进行特征点匹配的示例代码:
# 创建 BFMatcher 对象
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
# 计算特征描述符
keypoints1, descriptors1 = orb.detectAndCompute(img1, None)
keypoints2, descriptors2 = orb.detectAndCompute(img2, None)
keypoints3, descriptors3 = orb.detectAndCompute(img3, None)
keypoints4, descriptors4 = orb.detectAndCompute(img4, None)
# 匹配特征点
matches1_2 = bf.match(descriptors1, descriptors2)
matches1_3 = bf.match(descriptors1, descriptors3)
matches1_4 = bf.match(descriptors1, descriptors4)
# 绘制匹配结果
img_matches1_2 = cv2.drawMatches(img1, keypoints1, img2, keypoints2, matches1_2, None)
img_matches1_3 = cv2.drawMatches(img1, keypoints1, img3, keypoints3, matches1_3, None)
img_matches1_4 = cv2.drawMatches(img1, keypoints1, img4, keypoints4, matches1_4, None)
cv2.imshow('Matches 1-2', img_matches1_2)
cv2.imshow('Matches 1-3', img_matches1_3)
cv2.imshow('Matches 1-4', img_matches1_4)
cv2.waitKey(0)
以上代码将计算每对图像之间的特征描述符,并使用 BFMatcher 进行匹配。然后,使用 cv2.drawMatches 函数绘制匹配结果。
原文地址: https://www.cveoy.top/t/topic/koJ5 著作权归作者所有。请勿转载和采集!