python - 在 Python 中找到最匹配的 block /补丁

标签 python arrays window patch matching

<分区>

我希望在以较大二维阵列的 (x,y) 位置为中心的 WxW 窗口中找到最接近匹配的 NxN block 。下面的代码工作正常,但对于我的需要来说速度很慢,因为我需要多次运行此操作。有一个更好的方法吗?? 这里N=3,W=15,x=15,y=15并且(bestx,besty)是最佳匹配 block 的中心

import numpy as np

## Generate some test data
CurPatch = np.random.randint(20, size=(3, 3))
Data = np.random.randint(20,size=(30,30))

# Current Location 
x,y = 15,15
# Initialise Best Match
bestcost = 999.0
bestx = 0;besty=0

for Wy in xrange(-7,8):
    for Wx in xrange(-7,8):
            Ywj,Ywi = y+Wy,x+Wx 

            cost = 0.0
            for py in xrange(3):
                for px in xrange(3):
                    cost += abs(Data[Ywj+py-1,Ywi+px-1] - CurPatch[py,px]) 

            if cost < bestcost:
                bestcost = cost
                besty,bestx = Ywj,Ywi

print besty,bestx

最佳答案

正如我在评论中所说,您可以检查 for px in xrange(3) 中的 cost 是否大于或等于 bestcost: 如果是这样你可以中断,那样你可以节省很多不必要的迭代

示例(灯光会改变以强调较大迭代的差异):

import numpy as np
import time

## Generate some test data
CurPatch = np.random.randint(100, size=(3, 3))
Data = np.random.randint(100, size=(3000,3000))

# Current Location 
x,y = 10, 10
# Initialise Best Match
bestcost = 999.0
bestx = 0;besty=0

t0 = time.time()
for Wy in xrange(-7,50):
    for Wx in xrange(-7,50):
            Ywj, Ywi = y+Wy, x+Wx

            cost = 0.0
            for py in xrange(3):
                for px in xrange(3):
                    cost += abs(Data[Ywj+py-1,Ywi+px-1] - CurPatch[py,px])
                    if cost >= bestcost:
                        break

            if cost < bestcost:
                bestcost = cost
                besty,bestx = Ywj,Ywi

print besty, bestx
print "time: {}".format(time.time() - t0)

将时间定在 26 毫秒

time: 0.0269999504089

没有中断的代码将输出 37 毫秒:

time: 0.0379998683929

此外,我还必须建议将此代码转换为函数。

关于python - 在 Python 中找到最匹配的 block /补丁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24287411/

相关文章:

c - Ncurses 菜单越界

python - 忽略前 N 个命中的 pycharm 断点

python - 如何使 QCombobox 可针对分层项目进行扩展?

python - Django:没有名为应用程序的模块

c - 关于数组的最终赋值问题

php - 在PHP中删除多维数组中特定键的重复值但删除最后一个?

javascript - 从 Chrome 本地存储保存和加载数据

WPF:类似浏览器的撕裂

macos - 如何以编程方式在 macOS SwiftUI 应用程序中打开设置窗口

python - 将文本 append 到文件。将文本添加到指定的 txt 文件。