python - 使用矩阵乘法的 numpy 模板匹配

标签 python numpy template-matching

我试图通过沿图像移动模板来将模板与二值图像(仅黑色和白色)相匹配。并返回模板与图像之间的最小距离,以及该最小距离确实出现的相应位置。例如:

图片:

0 1 0
0 0 1
0 1 1

模板:

0 1
1 1

此模板与位置 (1,1) 处的图像最匹配,然后距离将为 0。到目前为止,事情并不太难,我已经有了一些代码来实现这一点。

def match_template(img, template):
    mindist = float('inf')
    idx = (-1,-1)
    for y in xrange(img.shape[1]-template.shape[1]+1):
        for x in xrange(img.shape[0]-template.shape[0]+1):
        #calculate Euclidean distance
        dist = np.sqrt(np.sum(np.square(template - img[x:x+template.shape[0],y:y+template.shape[1]])))
        if dist < mindist:
            mindist = dist
            idx = (x,y)
    return [mindist, idx]

但是对于我需要的大小的图像(500 x 200 像素的图像和 250 x 100 像素的模板),这已经需要大约 4.5 秒,这太慢了。而且我知道使用矩阵乘法可以更快地完成同样的事情(在 matlab 中我相信这可以使用 im2col 和 repmat 完成)。谁能解释一下如何在 python/numpy 中做到这一点?

顺便说一句。我知道有一个 opencv matchTemplate 函数可以完全满足我的需要,但由于稍后我可能需要稍微更改代码,所以我更喜欢一个我完全理解并可以更改的解决方案。

谢谢!

编辑:如果有人能向我解释 opencv 如何在不到 0.2 秒内完成此操作,那也很棒。我已经快速浏览了源代码,但这些东西在我看来总是很复杂。

edit2:赛通代码

import numpy as np
cimport numpy as np

DTYPE = np.int
ctypedef np.int_t DTYPE_t

def match_template(np.ndarray img, np.ndarray template):
    cdef float mindist = float('inf')
    cdef int x_coord = -1
    cdef int y_coord = -1
    cdef float dist
    cdef unsigned int x, y
    cdef int img_width = img.shape[0]
    cdef int img_height = img.shape[1]
    cdef int template_width = template.shape[0]
    cdef int template_height = template.shape[1]
    cdef int range_x = img_width-template_width+1
    cdef int range_y = img_height-template_height+1
    for y from 0 <= y < range_y:
        for x from 0 <= x < range_x:
            dist = np.sqrt(np.sum(np.square(template - img[ x:<unsigned int>(x+template_width), y:<unsigned int>(y+template_height) ]))) #calculate euclidean distance
            if dist < mindist:
                mindist = dist
                x_coord = x
                y_coord = y
    return [mindist, (x_coord,y_coord)]

img = np.asarray(img, dtype=DTYPE)
template = np.asarray(template, dtype=DTYPE)
match_template(img, template)

最佳答案

一种可能的方法是通过卷积(可以是蛮力或 FFT)来做你想做的事。矩阵乘法 AFAIK 不起作用。您需要将数据与模板进行卷积。并找到最大值(您还需要进行一些缩放以使其正常工作)。

xs=np.array([[0,1,0],[0,0,1],[0,1,1]])*1.
ys=np.array([[0,1],[1,1]])*1.
print scipy.ndimage.convolve(xs,ys,mode='constant',cval=np.inf)
>>> array([[  1.,   1.,  inf],
       [  0.,   2.,  inf],
       [ inf,  inf,  inf]])

print scipy.signal.fftconvolve(xs,ys,mode='valid') 
>>> array([[ 1.,  1.],
           [ 0.,  2.]])

关于python - 使用矩阵乘法的 numpy 模板匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12715673/

相关文章:

用于抛硬币问题的 Python 代码

python - 使用 python 扩展、转置和解聚合数据集

opencv - 使用opencv cvMatchTemplate时,如何选择好的模板进行更精准的匹配?

opencv - 视频中的箭头识别

python - 如何在Python中计算平方和?

python - random.seed() 不适用于 random.choice()

python - AttributeError: 'module'对象没有属性 'cv'

python - 来自 tornado.httpclient.AsyncHTTPClient 的 PUT 请求

python - 如何在不导入 RAM 的情况下使用 numpy 文件?