On Windows platform performed the following installations
pip install opencv-python
pip install opencv-contrib-python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pip install opencv-python --upgrade | |
#pip install opencv-contrib-python --upgrade | |
#pip show opencv-python | |
#pip show opencv-contrib-python | |
#pip install opencv-contrib-python==3.3.0.9 | |
import numpy as np | |
import cv2 | |
import matplotlib.pyplot as plt | |
img1 = cv2.imread('B4.jpg',0) # queryImage | |
img2 = cv2.imread('SKU.jpg',0) # trainImage | |
sift = cv2.xfeatures2d.SIFT_create() | |
# find the keypoints and descriptors with SIFT | |
kp1, des1 = sift.detectAndCompute(img1,None) | |
kp2, des2 = sift.detectAndCompute(img2,None) | |
# BFMatcher with default params | |
bf = cv2.BFMatcher() | |
matches = bf.knnMatch(des1,des2, k=2) | |
# Apply ratio test | |
good = [] | |
for m,n in matches: | |
if m.distance < 0.7*n.distance: | |
good.append([m]) | |
img3 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,good,None,flags=2) | |
plt.imshow(img3),plt.show() | |
print('Number of matches - SIFT') | |
print(len(good)) | |
# FLANN parameters | |
FLANN_INDEX_KDTREE = 1 | |
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5) | |
search_params = dict(checks=100) # or pass empty dictionary | |
flann = cv2.FlannBasedMatcher(index_params,search_params) | |
matches = flann.knnMatch(des1,des2,k=2) | |
# Need to draw only good matches, so create a mask | |
matchesMask = [[0,0] for i in range(len(matches))] | |
# ratio test as per Lowe's paper | |
for i,(m,n) in enumerate(matches): | |
if m.distance < 0.7*n.distance: | |
matchesMask[i]=[1,0] | |
draw_params = dict(matchColor = (0,255,0), | |
singlePointColor = (255,0,0), | |
matchesMask = matchesMask, | |
flags = 0) | |
print('Number of matches - FLANN') | |
print(len(draw_params)) | |
img3 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,matches,None,**draw_params) | |
#plt.imshow(img3,),plt.show() | |
# Initiate ORB detector | |
orb = cv2.ORB_create() | |
# find the keypoints and descriptors with ORB | |
kp1, des1 = orb.detectAndCompute(img1,None) | |
kp2, des2 = orb.detectAndCompute(img2,None) | |
# create BFMatcher object | |
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) | |
# Match descriptors. | |
matches = bf.match(des1,des2) | |
# Sort them in the order of their distance. | |
matches = sorted(matches, key = lambda x:x.distance) | |
print('Number of matches - ORB') | |
print(len(matches)) | |
#Modified Original code with Minor Changes | |
#https://docs.opencv.org/3.3.0/dc/dc3/tutorial_py_matcher.html |