python – 使用矩阵乘法的numpy模板匹配
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 使用矩阵乘法的numpy模板匹配,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2519字,纯文字阅读大概需要4分钟。
内容图文
我试图通过沿着图像移动模板来匹配模板与二进制图像(仅黑色和白色).并返回模板和图像之间的最小距离,以及发生此最小距离的相应位置.例如:
IMG:
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:Cython代码
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模板匹配全部内容,希望文章能够帮你解决python – 使用矩阵乘法的numpy模板匹配所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。