PythonOpenCV-特征检测-对象查找
经过特征匹配后,可找到查询图像在训练图像中的最佳匹配,从而可在训练图像中精确查找到查询图像。获得最佳匹配结果后,调用 cv2.findHomography(函数执行查询图像和训练图像的透视转换,再调用 cv2.perspectiveTransform()函数执行向量的透视矩阵转换,可获得查询图像在训练图像中的位置。
cv2.findHomography()函数的基本格式如下:
retv, mask = cv2.findHomography(srcPoints,dstPoints[, method[, ransacReproiThreshold]])
参数说明:
retv:返回的转换矩阵
mask:返回的查询图像在训练图像中的最佳匹配结果掩模
srcPoints:查询图像匹配结果的坐标
dstPoints :训练图像匹配结果的坐标
method:用于计算透视转换矩阵的方法
ransacReproiThreshold:可允许的最大重投影误差
cv2.perspectiveTransform()函数的基本格式如下:
dst = cv2.perspectiveTransform(src,m)
参数说明:
src:输入的 2 通道或 3 通道浮点类型的数组
m:大小为3x3或4x4 的浮点类型的转换矩阵,如使用 cv2findHomography0函数返回的转换矩阵
dst:输出结果数组,大小和类型与 src 相同
代码示例:
import cv2 as cv import numpy as np import matplotlib.pyplot as plt img1 = cv.imread('xhu3.jpg', cv.IMREAD_GRAYSCALE) # 打开灰度图像 img2 = cv.imread('xhu2.jpg', cv.IMREAD_GRAYSCALE) # 打开灰度图像 orb = cv.ORB_create() # 创建ORB检测器 kp1, des1 = orb.detectAndCompute(img1, None) # 检测关键点和计算描述符 kp2, des2 = orb.detectAndCompute(img2, None) # 检测关键点和计算描述符 bf = cv.BFMatcher_create(cv.NORM_HAMMING, crossCheck=True) # 创建匹配器 ms = bf.match(des1, des2) # 执行特征匹配 ms = sorted(ms, key=lambda x: x.distance) # 按距离排序 matchesMask = None if len(ms) > 10: # 在有足够数量的匹配结果时,才计算查询图像在目标图像中的位置 # 计算查询图像匹配结果的坐标 querypts = np.float32([kp1[m.queryIdx].pt for m in ms]).reshape(-1, 1, 2) # 计算训练图像匹配结果的坐标 trainpts = np.float32([kp2[m.trainIdx].pt for m in ms]).reshape(-1, 1, 2) # 查找查询图像和训练图像的透视转换 retv, mask = cv.findHomography(querypts, trainpts, cv.RANSAC) # 计算最佳匹配结果的掩模,用于绘制匹配结果 matchesMask = mask.ravel().tolist() h, w = img1.shape pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2) # 执行向量的透视矩阵转换,获得查询图像在训练图像中的位置 dst = cv.perspectiveTransform(pts, retv) # 用白色矩形框在训练图像中绘制查询图像的范围 img2 = cv.polylines(img2, [np.int32(dst)], True, (255, 255, 255), 5) img3 = cv.drawMatches(img1, kp1, img2, kp2, ms, None, matchColor=(0, 255, 0), # 用绿色绘制匹配结果 singlePointColor=None, matchesMask=matchesMask, # 绘制掩模内的匹配结果 flags=cv.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS) plt.imshow(img3) plt.axis('off') plt.show()
/*-------------------------------------------------------------------------------------------------------
笔者说明:
该笔记来源于本人学习Python + OpenCv时的资料,
分享出来只是为了供大家学习,并且为了自己以后想要用的时候方便寻找。
时间:2023年9月3日
------------------------------------------------------------------------------------------------------------*/

PythonOpenCV-特征检测-对象查找
浙公网安备 33010602011771号