close

使用 OpenCV 比較兩張圖片的特徵匹配

本教學展示如何使用 OpenCV 的 SURF 特徵檢測與 BFMatcher,對兩張圖片進行特徵匹配並視覺化結果。

程式碼範例與註解

# 匯入必要模組
import cv2


# 加載圖片
img1 = cv2.imread('box.png')
img2 = cv2.imread('box_in_scene.png')

# 初始化特徵檢測器
feature = cv2.xfeatures2d.SURF_create()

# 檢測並計算特徵點與描述子
kp1, des1 = feature.detectAndCompute(img1, None)
kp2, des2 = feature.detectAndCompute(img2, None)

# 使用 BFMatcher 進行特徵匹配
bf = cv2.BFMatcher()
matches = bf.knnMatch(des1, des2, k=2)

# 篩選優良匹配點
good = []
for m, n in matches:
    if m.distance < 0.55 * n.distance:
        good.append(m)

print('Matching points :{}'.format(len(good)))

# 繪製匹配結果
img3 = cv2.drawMatchesKnn(img1, kp1, img2, kp2, [good], outImg=None, 
        flags=cv2.DRAW_MATCHES_FLAGS_NOT_DRAW_SINGLE_POINTS)

# 調整輸出圖片大小
width, height, channel = img3.shape
ratio = float(width) / float(height)
img3 = cv2.resize(img3, (1024, int(1024 * ratio)))

# 顯示結果
cv2.imshow('video', img3)
cv2.waitKey(0)
cv2.destroyAllWindows()

  

程式解析

  • 加載圖片: 使用 cv2.imread 讀取圖片。
  • 特徵檢測: 使用 SURF 特徵檢測器計算每張圖片的特徵點和描述子。
  • 特徵匹配: 使用 BFMatcher 進行特徵匹配,並通過 knnMatch 返回每個特徵的兩個最佳匹配點。
  • 篩選匹配點: 通過設置距離閾值,篩選優良匹配點。
  • 繪製匹配結果: 使用 cv2.drawMatchesKnn 繪製匹配點,並調整輸出圖片的大小。
  • 顯示結果: 使用 cv2.imshow 顯示最終的匹配結果。

結論

本程式展示了如何使用 OpenCV 進行圖片間的特徵匹配。SURF 特徵檢測與 BFMatcher 的結合可以高效地對比兩張圖片的相似性。您可以通過調整參數(如距離閾值)進一步優化匹配結果。

arrow
arrow
    創作者介紹
    創作者 liusming 的頭像
    liusming

    劉老師的跨域創想工坊

    liusming 發表在 痞客邦 留言(2) 人氣()