日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發布時間:2025/3/21 python 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python乘法模板_python – 使用矩阵乘法的numpy模板匹配 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我試圖通過沿著圖像移動模板來匹配模板與二進制圖像(僅黑色和白色).并返回模板和圖像之間的最小距離,以及發生此最小距離的相應位置.例如:

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:(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)

總結

以上是生活随笔為你收集整理的python乘法模板_python – 使用矩阵乘法的numpy模板匹配的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。