# matcher

import os
import shutil

import cv2

def xmkdir(dst):
    shutil.rmtree(dst, ignore_errors=True)
    os.makedirs(dst)
    return dst

def walk(fn, src, dst):
    for path in os.listdir(src):
        cv2.imwrite(dst + path, fn(cv2.imread(src + path)))

def template_match():
    img0 = cv2.imread('./gc.png', cv2.IMREAD_GRAYSCALE)
    img0_w, img0_h = img0.shape
    def walker(img):
        gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        result = cv2.matchTemplate(gray_img, img0, cv2.TM_CCOEFF)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
        cv2.rectangle(img, max_loc, (max_loc[0] + img0_w, max_loc[1] + img0_h), 255, 2)
        return img
    walk(walker, './src/', xmkdir('./dst/template/'))

def akaze_match():
    detector = cv2.AKAZE_create()
    matcher = cv2.BFMatcher()
    img0 = cv2.imread('./gc.png', cv2.IMREAD_GRAYSCALE)
    img0_w, img0_h = img0.shape
    kp0, des0 = detector.detectAndCompute(img0, None)
    def walker (img):
        gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        kp1, des1 = detector.detectAndCompute(gray_img, None)
        matches = matcher.knnMatch(des0, des1, k=2)
        return cv2.drawMatchesKnn(img0, kp0, img, kp1, matches, None)
    walk(walker, './src/', xmkdir('./dst/akaze/'))

if __name__ == '__main__':
    template_match()
    akaze_match()
