小编Sem*_*emi的帖子

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

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

图片:

0 1 0
0 0 1
0 1 1
Run Code Online (Sandbox Code Playgroud)

模板:

0 1
1 1
Run Code Online (Sandbox Code Playgroud)

该模板与位置 (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]
Run Code Online (Sandbox Code Playgroud)

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

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

python numpy template-matching

5
推荐指数
1
解决办法
3550
查看次数

使用函数编辑字符串

我试图通过将它传递给mutate()来编辑一个字符串,见下文.

简化示例:

fn mutate(string: &mut &str) -> &str {
    string[0] = 'a'; // mutate string
    string
}

fn do_something(string: &str) {
    println!("{}", string);
}

fn main() {
    let string = "Hello, world!";
    loop {
        string = mutate(&mut string);
        do_something(string);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我得到以下编译错误:

main.rs:1:33: 1:37 error: missing lifetime specifier [E0106]
main.rs:1 fn mutate(string: &mut &str) -> &str {
                                          ^~~~
main.rs:1:33: 1:37 help: this function's return type contains a borrowed value, but the signature does not say which one of `string`'s 2 …
Run Code Online (Sandbox Code Playgroud)

lifetime rust

1
推荐指数
1
解决办法
2215
查看次数

标签 统计

lifetime ×1

numpy ×1

python ×1

rust ×1

template-matching ×1