1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| import numpy as np
import cv2
from matplotlib import pyplot as plt
nameImg1 = 'img/knight.jpg'
nameImg2 = 'img/h1.jpg'
img1 = cv2.imread(nameImg1,0)
fast1 = cv2.FastFeatureDetector_create()
kp1 = fast1.detect(img1,None)
brisk1 = cv2.BRISK_create();
kp1, des1 = brisk1.compute(gray1, kp1)
img2 = cv2.imread(nameImg2,0)
fast2 = cv2.FastFeatureDetector_create()
kp2 = fast2.detect(img2,None)
brisk2 = cv2.BRISK_create();
kp2, des2 = brisk2.compute(gray2, kp2)
MIN_MATCH_COUNT = 10
# 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])
# cv2.drawMatchesKnn expects list of lists as matches.
img3 = cv2.imread('', 0)
img3 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,good,img3,flags=2)
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 = cv2.findHomography(src_pts, dst_pts, cv2.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 = cv2.perspectiveTransform(pts,M)
img2 = cv2.polylines(img2,[np.int32(dst)],True,255,3, cv2.LINE_AA)
else:
#print "Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT)
print ("Not enough matchs are found")
matchesMask = None
draw_params = dict(matchColor = (0,255,0), # draw matches in green color
singlePointColor = None,
matchesMask = matchesMask, # draw only inliers
flags = 2)
img4 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,good,None,flags=2)
plt.imshow(img3, 'gray'),plt.show() |
Partager