import cv2
import numpy as np
from matplotlib import pyplot as plt


def find_shift(image, patern):

    img1 = 1 - image / 255 # in opencv 255 is white this conver black to 1
                          # and white to 0
    
    img2 = np.zeros(img1.shape)
    # add zero padding to obj
    img2[0:patern.shape[0],0:patern.shape[1]] = 1 - patern / 255

    f1 = np.fft.fft2(img1)
    f2 = np.fft.fft2(img2)
    f_res = np.multiply(f1, np.conj(f2))
    res = np.fft.ifft2(f_res)

    y,x =  np.unravel_index(np.argmax(np.real(res)),res.shape)
    return x, y 

dom = cv2.imread('bin_images/dom.png',0)
okno = cv2.imread('bin_images/okno.png',0)

shift = find_shift(dom, okno)
print(shift)



res = cv2.cvtColor(dom,cv2.COLOR_GRAY2RGB)
cv2.rectangle(res,shift,(shift[0]+okno.shape[1],shift[1]+okno.shape[0]),(0,0,255),2)
cv2.imshow('found',res)
cv2.imwrite('found.png',res)
cv2.waitKey(1)
