<p>我使用相对较新的NumPy方法<a href="https://numpy.org/devdocs/reference/generated/numpy.lib.stride_tricks.sliding_window_view.html#numpy-lib-stride-tricks-sliding-window-view" rel="nofollow noreferrer">sliding_window_view</a>找到了一个解决方案</p>
<blockquote>
<p>Create a sliding window view into the array with the given window shape.</p>
<p>Also known as rolling or moving window, the window slides across all dimensions of
the array and extracts subsets of the array at all window positions.</p>
<p>New in version 1.20.0.</p>
</blockquote>
<p><em>注意:由于兼容性问题,我已在新的虚拟环境中安装了最新的NumPy版本</em></p>
<p>检查滑动窗口视图如何工作的简单测试:</p>
<pre><code>import numpy as np
from numpy.lib.stride_tricks import sliding_window_view
t = np.array([[ [0,0,0], [1,1,1]],
[ [2,2,2], [3,3,3]]])
x = np.array([[ [0,0,0], [1,1,1], [2,2,2], [3,3,3]],
[[10,10,10], [11,11,11], [12,12,12], [13,13,13]],
[[20,20,20], [21,21,21], [22,22,22], [23,23,23]]])
x[1:3, 1:3, :] = t # Copy t to x - it looks like there is a problem along edges
v = sliding_window_view(x, (2,2,3))
print(v-t)
</code></pre>
<p>结果开始于:</p>
<pre><code>[[[[[[ 0 0 0]
[ 0 0 0]]
</code></pre>
<p>这意味着<code>t</code>按预期从<code>v</code>的所有“窗口”中减去</p>
<hr/>
<p>为测试<a href="https://numpy.org/doc/stable/reference/generated/numpy.all.html" rel="nofollow noreferrer">np.all</a>添加以下命令:</p>
<pre><code>print(np.where((v == t).all(axis=(3, 4, 5))))
</code></pre>
<p>输出为:</p>
<pre><code>(array([1], dtype=int64), array([1], dtype=int64), array([0], dtype=int64))
</code></pre>
<p>如果沿轴3、4和5的所有元素都是<code>True</code>,则<code>all(axis=(3, 4, 5))</code>为<code>True</code>。<br/>
在上面的示例中,我们在索引[1,1]中找到了一个匹配项</p>
<hr/>
<p>以下是检测完美匹配的解决方案(使用NumPy):</p>
<pre><code>import cv2
import numpy as np
from numpy.lib.stride_tricks import sliding_window_view
# Read the images from the file
small_image = cv2.imread('ran_away.png')
#small_image = cv2.imread('icon.png');
large_image = cv2.imread('pokemon_card.png')
v = sliding_window_view(large_image, small_image.shape)
match_idx = np.where((v == small_image).all(axis=(3, 4, 5)))
if len(match_idx[0]) > 0:
row = match_idx[0][0]
col = match_idx[1][0]
cv2.rectangle(large_image, (col, row), (col+small_image.shape[1], row+small_image.shape[1]), (0, 255, 0), 2)
cv2.imshow('large_image', large_image)
cv2.waitKey()
cv2.destroyAllWindows()
</code></pre>
<hr/>
<p>结果:<br/>
<a href="https://i.stack.imgur.com/9ZFuU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9ZFuU.png" alt="enter image description here"/></a></p>