import cv2
import sys
import os
import numpy as np

def find_image_in_image(image_path1, image_path2, scales=None, threshold=0.8):
    # 이미지를 컬러로 읽어옵니다.
    img1 = cv2.imread(image_path1, cv2.IMREAD_COLOR)
    img2 = cv2.imread(image_path2, cv2.IMREAD_COLOR)
    
    # 이미지가 제대로 로드되었는지 확인합니다.
    if img1 is None:
        print("img load error1")
        return 0
    if img2 is None:
        print("img load error2")
        return 0

    best_val = -1  # 가장 높은 매칭 값을 저장할 변수
    best_loc = None  # 가장 높은 매칭 위치를 저장할 변수
    best_scale = 1.0  # 가장 높은 매칭을 기록한 스케일
    
    if scales is None:
        scales = np.arange(0.8, 1.5, 0.03)

    # 여러 스케일로 템플릿 매칭 수행
    for scale in scales:
        resized_template = cv2.resize(img2, None, fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR)
        result = cv2.matchTemplate(img1, resized_template, cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
        
        if max_val > best_val:
            best_val = max_val
            best_loc = max_loc
            best_scale = scale
            best_template_size = resized_template.shape[1::-1]  # (width, height)


    top_left = best_loc
    bottom_right = (top_left[0] + best_template_size[0], top_left[1] + best_template_size[1])
        
    # img1에 사각형 그리기
    cv2.rectangle(img1, top_left, bottom_right, (0, 255, 0), 2)  # 초록색 사각형

    # 결과 이미지 저장
    #result_image_path = '/var/www/html/api/img_chk/matched_image.png'
    #cv2.imwrite(result_image_path, img1)
    return best_val

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("error")
        sys.exit(1)
    script_dir = os.path.dirname(os.path.abspath(__file__))
    image_path1 = os.path.join(script_dir, sys.argv[1])
    image_path2 = os.path.join(script_dir, sys.argv[2])
    
    # 이미지 비교 수행
    result = find_image_in_image(image_path1, image_path2)
    print(result)
