在Numpy图像中查找子图像 [英] Finding a subimage inside a Numpy image

查看:281
本文介绍了在Numpy图像中查找子图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个从PIL图像转换的Numpy数组(3维uint8)。

I have two Numpy arrays (3-dimensional uint8) converted from PIL images.

我想找到第一个图像是否包含第二个图像,如果是,找出匹配所在的第一张图片内左上角像素的坐标。

I want to find if the first image contains the second image, and if so, find out the coordinates of the top-left pixel inside the first image where the match is.

有没有办法在Numpy中做到这一点,速度够快方式,而不是使用(4!非常慢)纯Python循环?

Is there a way to do that purely in Numpy, in a fast enough way, rather than using (4! very slow) pure Python loops?

2D示例:

a = numpy.array([
    [0, 1,  2,  3],
    [4, 5,  6,  7],
    [8, 9, 10, 11]
])
b = numpy.array([
    [2, 3],
    [6, 7]
])

如何做这样的事情?

position = a.find(b)

position 然后是(0,2)

推荐答案

这可以使用scipy的 correlate2d 然后使用 argmax 在互相关中找到峰值。

This can be done using scipy's correlate2d and then using argmax to find the peak in the cross-correlation.

这里有一个关于数学和思想的更完整的解释,以及一些例子。

Here's a more complete explanation of the math and ideas, and some examples.

如果你想要保持纯粹的Numpy甚至不使用scipy,或者如果图像很大,你可能最好使用基于FFT的方法来进行交叉相关。

If you want to stay in pure Numpy and not even use scipy, or if the images are large, you'd probably be best using an FFT based approach to the cross-correlations.

编辑:问题特别要求纯Numpy解决方案。但是如果你可以使用OpenCV或其他图像处理工具,使用其中一种显然更容易。以下是PiQuer给出的一个例子,如果你可以使用的话,我建议你这样做。

The question specifically asked for a pure Numpy solution. But if you can use OpenCV, or other image processing tools, it's obviously easier to use one of these. An example of such is given by PiQuer below, which I'd recommend if you can use it.

这篇关于在Numpy图像中查找子图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆