python sift 特徵匹配 圖片相似度

CV計算機視覺工程師發表於2020-12-30

一、sift匹配影像相似度原理

可以從圖片中提取SIFT特徵,對兩幅圖片的SIFT特徵進行匹配並按照一定條件刪選就能得到兩幅圖片的匹配點個數,匹配點個數越多,相似度越高

二、指令碼

import cv2
from matplotlib import pyplot as plt
import numpy as np
import os
import math


def getMatchNum(matches,ratio):
    '''返回特徵點匹配數量和匹配掩碼'''
    matchesMask=[[0,0] for i in range(len(matches))]
    matchNum=0
    for i,(m,n) in enumerate(matches):
        if m.distance<ratio*n.distance: #將距離比率小於ratio的匹配點刪選出來
            matchesMask[i]=[1,0]
            matchNum+=1
    return (matchNum,matchesMask)

path='G:\DeepLearning\data\sift/'
queryPath=path
samplePath=path+'1.jpg' #樣本圖片
comparisonImageList=[] #記錄比較結果

#建立SIFT特徵提取器
sift = cv2.xfeatures2d.SIFT_create() 
#建立FLANN匹配物件
FLANN_INDEX_KDTREE=0
indexParams=dict(algorithm=FLANN_INDEX_KDTREE,trees=5)
searchParams=dict(checks=50)
flann=cv2.FlannBasedMatcher(indexParams,searchParams)

sampleImage=cv2.imread(samplePath,0)
kp1, des1 = sift.detectAndCompute(sampleImage, None) #提取樣本圖片的特徵
for parent,dirnames,filenames in os.walk(queryPath):
    for p in filenames:
        p=queryPath+p
        queryImage=cv2.imread(p,0)
        kp2, des2 = sift.detectAndCompute(queryImage, None) #提取比對圖片的特徵
        matches=flann.knnMatch(des1,des2,k=2) #匹配特徵點,為了刪選匹配點,指定k為2,這樣對樣本圖的每個特徵點,返回兩個匹配
        (matchNum,matchesMask)=getMatchNum(matches,0.9) #通過比率條件,計算出匹配程度
        matchRatio=matchNum*100/len(matches)
        drawParams=dict(matchColor=(0,255,0),
                singlePointColor=(255,0,0),
                matchesMask=matchesMask,
                flags=0)
        comparisonImage=cv2.drawMatchesKnn(sampleImage,kp1,queryImage,kp2,matches,None,**drawParams)
        comparisonImageList.append((comparisonImage,matchRatio)) #記錄下結果

comparisonImageList.sort(key=lambda x:x[1],reverse=True) #按照匹配度排序
count=len(comparisonImageList)
column=4
row=math.ceil(count/column)
#繪圖顯示
figure,ax=plt.subplots(row,column)
for index,(image,ratio) in enumerate(comparisonImageList):
    ax[int(index/column)][index%column].set_title('Similiarity %.2f%%' % ratio)
    ax[int(index/column)][index%column].imshow(image)
plt.show()


# 三.結果
別結果看看就好,不指望傳統演算法了,手動哭
![在這裡插入圖片描述](https://img-blog.csdnimg.cn/20201230023124143.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2p1YW5qaTM3OTg=,size_16,color_FFFFFF,t_70#pic_center)



相關文章