Matlab Template Matching Using FFT

前端 未结 2 895
天命终不由人
天命终不由人 2020-12-01 09:50

I am struggling with template matching in the Fourier domain in Matlab. Here are my images (the artist is RamalamaCreatures on DeviantArt):

My aim is to p

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 10:38

    Just ended up implementing the same with python with similar ideas as @rayryeng's using scipy.fftpack.fftn() / ifftn() functions with the following result on the same target and template images:

    import numpy as np
    import scipy.fftpack as fp
    from skimage.io import imread
    from skimage.color import rgb2gray, gray2rgb
    import matplotlib.pylab as plt
    from skimage.draw import rectangle_perimeter
    
    im = 255*rgb2gray(imread('http://i.stack.imgur.com/FXEy7.jpg'))    # target
    im_tm = 255*rgb2gray(imread('http://i.stack.imgur.com/6bTzT.jpg')) # template
    
    # FFT 
    F = fp.fftn(im)                   
    F_tm = fp.fftn(im_tm, shape=im.shape)
    
    # compute the best match location
    F_cc = F * np.conj(F_tm)
    c = (fp.ifftn(F_cc/np.abs(F_cc))).real
    i, j = np.unravel_index(c.argmax(), c.shape)
    print(i, j)
    # 214 317
    
    # draw rectangle around the best match location
    im2 = (gray2rgb(im)).astype(np.uint8)
    rr, cc = rectangle_perimeter((i,j), end=(i + im_tm.shape[0], j + im_tm.shape[1]), shape=im.shape)
    for x in range(-2,2):
        for y in range(-2,2):
            im2[rr + x, cc + y] = (255,0,0)
    
    # show the output image
    plt.figure(figsize=(10,10))
    plt.imshow(im2)
    plt.axis('off')
    plt.show()
    

    Also, the below animation shows the result obtained while locating a bird's template image inside a set of (target) frames extracted from a video with a flock of birds.

    One thing to note: the output is very much dependent on the similarity of the size and shape of the object that is to be matched with the template, if it's quite different from that of the template image, the template may not be matched at all.

提交回复
热议问题