30.OpenCV的特征檢測——物件查找
文章目錄
- 前言
- 一、物件查找
- 二、OpenCV-Python資源下載
- 總結
前言
??經過特征匹配后,可找到查詢影像在訓練影像中的最佳匹配,從而可在訓練影像中精確查找到查詢影像,
一、物件查找
獲得最佳匹配結果后,呼叫cv2.findHomography()函式執行查詢影像和訓練影像的透視轉換,在呼叫cv2.perspectiveTransform()函式執行向量的透視矩陣轉換,可獲取查詢影像在訓練影像中的位置,
??OpenCV的cv2.findHomography()函式的基本格式如下:
retv, mask = cv2.findHomography(srcPoints, dstPoint[, method[, ransacReporjThreshold]])
retv為回傳的轉換矩陣
mask為回傳的查詢影像在訓練影像中的最佳匹配結果掩膜
srcPoints為查詢影像匹配結果的坐標
dstPoint為訓練影像匹配結果的坐標
method為用于計算透視轉換矩陣的方法
ransacReporjThreshold為可允許的最大重投影誤差
??OpenCV的cv2.perspectiveTransform()函式的基本格式如下:
dst = cv2.perspectiveTransform(src, m)
dst為輸出結果陣列, 大小和型別與src相同
src為輸入的2通道或3通道浮點型別陣列
m是大小為3*3或4*4的浮點型別的轉換矩陣, 如使用v2.findHomography()函式回傳的轉換矩陣
# 物件查找
import cv2
import numpy as np
img1 = cv2.imread("XIAN1.jpg" )
img2 = cv2.imread("XIAN2.jpg" )
orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)
bf = cv2.BFMatcher_create(cv2.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 = cv2.findHomography(querypts, trainpts, cv2.RANSAC)
# 計算最佳匹配結果的掩膜,用于繪制匹配匹配結果
matchesMask = mask.ravel().tolist()
h, w, c = img1.shape
pts = np.float32([[0,0], [0,h-1], [w-1,h-1], [w-1,0]]).reshape(-1,1,2)
# 執行向量的透視矩陣轉換,獲得查詢影像在訓練影像中的位置
dst = cv2.perspectiveTransform(pts,retv)
# 用白色的矩形在訓練影像中繪制出查詢影像的范圍
img2 = cv2.polylines(img2, [np.int32(dst)], True, (255,255,255),5)
img3 = cv2.drawMatches(img1, kp1, img2, kp2, ms, None,
matchColor = (0,255,0),
singlePointColor = (255,0,0),
matchesMask = matchesMask,
flags = cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
cv2.cv2.namedWindow("Result img", cv2.WINDOW_NORMAL)
cv2.imshow("Result img",img3)
cv2.waitKey(0)
cv2.destroyAllWindows()

二、OpenCV-Python資源下載
OpenCV-Python測驗用圖片、中文官方檔案、opencv-4.5.4原始碼
總結
??以上內容介紹了OpenCV-Python特征檢測中的物件查找,有關Python、資料科學、人工智能等文章后續會不定期發布,請大家多多關注,一鍵三連喲(●’?’●),
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/400407.html
標籤:其他
上一篇:GitHub 7.5k star量,各種視覺Transformer的PyTorch實作合集整理好了
下一篇:深度強化學習-策略梯度演算法推導
