python乘法模板_python – 使用矩阵乘法的numpy模板匹配
我試圖通過沿著圖像移動模板來匹配模板與二進制圖像(僅黑色和白色).并返回模板和圖像之間的最小距離,以及發(fā)生此最小距離的相應位置.例如:
IMG:
0 1 0
0 0 1
0 1 1
模板:
0 1
1 1
這個模板匹配位置(1,1)處的最佳圖像,然后距離將為0.到目前為止,事情并不太困難,我已經(jīng)有了一些代碼來完成這個技巧.
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之間的模板)這已經(jīng)花了大約4.5秒,這太慢了.而且我知道使用矩陣乘法可以更快地完成同樣的事情(在matlab中我相信這可以使用im2col和repmat完成).任何人都可以解釋我如何在python / numpy中做到這一點?
順便說一句.我知道有一個opencv matchTemplate函數(shù)可以完全滿足我的需要,但是因為我可能需要稍后更改代碼,所以我更喜歡一個我完全理解并可以改變的解決方案.
謝謝!
編輯:如果有人能解釋我opencv如何在不到0.2秒的時間內(nèi)做到這一點,那也很棒.我已經(jīng)對源代碼進行了簡短的介紹,但這些東西對我來說總是看起來很復雜.
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:(x+template_width), y:(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)
總結(jié)
以上是生活随笔為你收集整理的python乘法模板_python – 使用矩阵乘法的numpy模板匹配的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中接口测试垃圾数据如何清理_
- 下一篇: mysql语言的简介_谁能帮我介绍一下