#!/usr/bin/python3

import sys
import cv2

img = None
templ = None

def main(argv):
    if (len(sys.argv) < 2):
        raise TypeError('Not enough parameters'\
            'Usage:\search-image.py <image_name> <template_name>')

    global img
    global templ
    img = cv2.imread(sys.argv[1], cv2.IMREAD_COLOR)
    templ = cv2.imread(sys.argv[2], cv2.IMREAD_COLOR)

    if (len(sys.argv) > 3):
        raise TypeError('Too many parameters'\
                'Usage:\search-image.py <image_name> <template_name>')

    if ((img is None) or (templ is None)):
        raise TypeError('Can\'t read one of the images')

    MatchingMethod()

    return 0

def MatchingMethod():

    img_display = img.copy()

    result = cv2.matchTemplate(img, templ, cv2.TM_CCOEFF_NORMED)

    minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(result, None)

    matchLoc = maxLoc

    if (maxVal > 0.8):
        print('image found in', matchLoc)
        print('confidence', maxVal)
    else:
        print('image not found', matchLoc)
        print('confidence', maxVal)
        raise ValueError('confidence is too small: image not found')
    pass

if __name__ == "__main__":
    main(sys.argv[1:])
