import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img1 = cv.resize(cv.imread('../input/monalisa/mona.jpg',cv.IMREAD_GRAYSCALE), (0,0), fx=0.5, fy=0.5)
img2 = cv.resize(cv.imread('../input/monalisa/3.jpg',cv.IMREAD_GRAYSCALE), (0,0), fx=0.5, fy=0.5)
# Initiate AKAZE detector
detector = cv.AKAZE_create()
"""
# Basics of Brute-Force Matcher
"""
"""
Brute-Force Matching with KAZE Descriptors and Ratio Test

This time, we will use BFMatcher.knnMatch() to get k best matches. In this example, we will take k=2 so that we can apply ratio test explained by D.Lowe in his paper
"""
# find the keypoints and descriptors with AKAZE
kp1, des1 = detector.detectAndCompute(img1,None)
kp2, des2 = detector.detectAndCompute(img2,None)
# ([], [])
imgL = cv.drawKeypoints(img1, kp1, None, color=(0,0,255), flags=0)
imgR = cv.drawKeypoints(img2, kp2, None, color=(0,0,255), flags=0)
# BFMatcher with default params
bf = cv.BFMatcher()
matches = bf.knnMatch(des1,des2,k=2)
# Apply ratio test
good = []
for m,n in matches:
    if m.distance < 0.75*n.distance:
        good.append([m])
# cv.drawMatchesKnn expects list of lists as matches.
img3 = cv.drawMatchesKnn(img1,kp1,img2,kp2,good,None,flags=cv.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
plt.figure(figsize=(16, 16))
plt.title('AKAZE Interest Points')
plt.imshow(img3)
plt.show()
"""
# Feature Matching + Homography to find Objects
"""
"""
Now, we will mix up the feature matching and findHomography from calib3d module to find known objects in a complex image
"""
MIN_MATCH_COUNT = 10
# store all the good matches as per Lowe's ratio test.
good = []
for m,n in matches:
    if m.distance < 0.7*n.distance:
        good.append(m)

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 = cv.findHomography(src_pts, dst_pts, cv.RANSAC,5.0)
    matchesMask = mask.ravel().tolist()
    h, w  = img1.shape
    d  = img1.shape
    pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)
    dst = cv.perspectiveTransform(pts,M)
    img2 = cv.polylines(img2,[np.int32(dst)],True,255,3, cv.LINE_AA)
else:
    print( "Jumlah Key Point : {}/{}".format(len(good), MIN_MATCH_COUNT) )
    matchesMask = None

draw_params = dict(matchColor = (0,255,0), # draw matches in green color
                   singlePointColor = None,
                   matchesMask = matchesMask, # draw only inliers
                   flags = 2)
img3 = cv.drawMatches(img1,kp1,img2,kp2,good,None,**draw_params)
plt.figure(figsize=(20, 20))
plt.title('Feature Matching + Homography to find Objects with AKAZE Algorithm')
plt.imshow(img3, 'gray'),plt.show()