import cv2
import numpy as np
img1 = cv2.imread('./image/min_cat.png')
img2 = cv2.imread('./image/cat.png')
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
sift = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(gray1,None)
kp2, des2 = sift.detectAndCompute(gray2,None)
index_params = dict(algorithm = 1, trees = 5)
search_params = dict(checks = 50)
flann = cv2.FlannBasedMatcher(index_params,search_params)
matches = flann.knnMatch(des1,des2,k=2)
goods = []
for (m,n) in matches:
if m.distance < 0.75*n.distance:
goods.append(m)
if len(goods) >=4:
src_points = np.float32([kp1[m.queryIdx].pt for m in goods]).reshape(-1,1,2)
dst_points = np.float32([kp2[m.trainIdx].pt for m in goods]).reshape(-1,1,2)
H , _ = cv2.findHomography(src_points,dst_points,cv2.RANSAC,5)
h,w = img1.shape[:2]
pts = np.float32([[0,0],[0,h-1],[w-1,h-1],[w-1,0]]).reshape(-1,1,2)
dst = cv2.perspectiveTransform(pts,H)
cv2.polylines(img2,[np.int32(dst)],True,(0,0,255),2)
else:
print('not enough point number to compute homography matrix')
exit()
ret = cv2.drawMatchesKnn(img1,kp1,img2,kp2,[goods],None)
cv2.imshow('ret',ret)
cv2.imshow('img2',img2)
cv2.waitKey(0)
cv2.destroyAllWindows()