應用特徵匹配和單應性變換從複雜圖像中查找已知對象

目標

本章節中,

  • 我們將結合特徵匹配,用calib3d模塊查找單應性以達到從複雜圖像中識別出已知對象的目的。

基本原理

上節課我們做了什麼?我們使用一個queryImage,在其中找到一些特徵點,我們使用另一個trainImage,也找到了這個圖像中的特徵,我們找到了它們之間的最佳匹配。簡而言之,我們在另一張雜亂的圖像中找到了一個物體的某些部分的位置。這些信息足以準確地在trainImage上找到目標。

為此,我們可以使用calib3d模塊中的一個函數,即cv.findHomography()。如果我們從這兩幅圖像中傳遞一組點,它就會找到那個物體的透視變換。然後我們可以使用cv.perspective tivetransform()來查找對象。它至少需要四個正確的點來找到轉換。我們已經看到,在匹配過程中可能會出現一些可能影響結果的錯誤。為了解決這個問題,算法使用RANSAC或least_mid(可以由標誌決定)。因此,提供正確估計的良好匹配稱為內點,其餘的稱為外點。findhomography()返回一個掩碼,該掩碼指定內點和外點。我們來測試一下:

代碼

首先,像往常一樣,讓我們在圖像中找到SIFT特性,並應用比值測試找到最佳匹配。

import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
MIN_MATCH_COUNT = 10
img1 = cv.imread('box.png',0) # queryImage
img2 = cv.imread('box_in_scene.png',0) # trainImage
# Initiate SIFT detector
sift = cv.xfeatures2d.SIFT_create()
# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)
FLANN_INDEX_KDTREE = 1
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)
flann = cv.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1,des2,k=2)
# store all the good matches as per Lowe's ratio test.
good = []
for m,n in matches:
if m.distance < 0.7*n.distance:
good.append(m)

現在,我們設置了一個條件,即至少有10個匹配項(MIN_MATCH_COUNT定義)在其中查找對象。否則,只需顯示一條消息,說明沒有足夠的匹配項。

如果找到足夠的匹配項,我們將提取兩個圖像中匹配的關鍵點的位置。它們被傳遞來尋找透視變換。一旦我們得到這個3x3變換矩陣,我們就用它把queryImage的角變換成trainImage中的對應點。然後畫出來。

if len(good)>MIN_MATCH_COUNT: 

src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)
dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)
M, mask = cv.findHomography(src_pts, dst_pts, cv.RANSAC,5.0)
matchesMask = mask.ravel().tolist()
h,w,d = 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,M)
img2 = cv.polylines(img2,[np.int32(dst)],True,255,3, cv.LINE_AA)
else:
print( "Not enough matches are found - {}/{}".format(len(good), MIN_MATCH_COUNT) )
matchesMask = None
Finally we draw our inliers (if successfully found the object) or matching keypoints (if failed).
draw_params = dict(matchColor = (0,255,0), # draw matches in green color
singlePointColor = None,
matchesMask = matchesMask, # draw only inliers
flags = 2)
img3 = cv.drawMatches(img1,kp1,img2,kp2,good,None,**draw_params)
plt.imshow(img3, 'gray'),plt.show()

參見下面的結果。在雜亂的圖像中,對象以白色標記:


openCV - 應用特徵匹配和單應性變換從複雜圖像中查找已知對象

到此為止,我們認真過了一遍openCV官網對圖像特徵點檢測提取匹配的各種算法,以及它們各自的優缺點,接下來的章節,看看怎麼運用這些算法到我們實際問題中來。


分享到:


相關文章: