我需要一个正在开发的 Python 程序,以便能够在大图像中找到小图像的精确像素匹配。我一直在使用以下函数,它是在 Stack Overflow 上回答有关如何进行此类图像匹配的问题时给出的一些代码的稍微修改的版本。看这里:Determine if an image exists within a larger image, and if so, find it, using Python
def find_image(im, tpl):
'''finds an exact, pixel for pixel match of tpl inside im, or raises an
exception'''
im = np.atleast_3d(im)
tpl = np.atleast_3d(tpl)
H, W, D = im.shape[:3]
h, w = tpl.shape[:2]
# Integral image and template sum per channel
sat = im.cumsum(1).cumsum(0)
tplsum = np.array([tpl[:, :, i].sum() for i in range(D)])
# Calculate lookup table for all the possible windows
iA, iB, iC, iD = sat[:-h, :-w], sat[:-h, w:], sat[h:, :-w], sat[h:, w:]
lookup = iD - iB - iC + iA
# Possible matches
possible_match = np.where(np.logical_and(*[lookup[..., i] == tplsum[i] for i in range(D)]))
# Find exact match
for y, x in zip(*possible_match):
if np.all(im[y+1:y+h+1, x+1:x+w+1] == tpl):
return (y+1, x+1)
raise Exception("Image not found")
这在大多数情况下都运行得非常好,但在一个非常重要的情况下,我遇到了以下错误。
possible_match = np.where(np.logical_and(*[lookup[..., i] == tplsum[i] for i in range(D)]))
ValueError:参数数量无效
我不知道是什么导致了这个问题,也不知道如何解决它。任何帮助将不胜感激。
请您参考如下方法:
logical_and 的文档指定了logical_and(x1, x2[, out])。它需要 2 或 3 个参数。如果您想比较 2 个数组以外的任何内容,则需要使用 logical_and.reduce。
例如:
In [703]: A=np.ones((4,3),np.bool)
In [704]: np.logical_and(*[a for a in A[:2,:]])
Out[704]: array([ True, True, True], dtype=bool)
In [705]: np.logical_and(*[a for a in A[:3,:]])
Out[705]: array([ True, True, True], dtype=bool)
In [706]: np.logical_and(*[a for a in A[:4,:]])
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-706-4ed655db12ce> in <module>()
----> 1 np.logical_and(*[a for a in A[:4,:]])
ValueError: invalid number of arguments
A[:1,:] 也会产生此错误(因为它只传递了 1 个参数)。
In [707]: np.logical_and.reduce([a for a in A[:2,:]])
Out[707]: array([ True, True, True], dtype=bool)
In [708]: np.logical_and.reduce([a for a in A[:3,:]])
Out[708]: array([ True, True, True], dtype=bool)
In [709]: np.logical_and.reduce([a for a in A[:4,:]])
Out[709]: array([ True, True, True], dtype=bool)
如果我的 A 不全是 True 可能会更有启发性。
我很困惑为什么 A[:3,:] 案例会运行,但后来意识到第三个数组被解释为 out 参数。它正在设置 A[2,:]=np.logical_and(A[0,:],A[1,:])。进一步证明 np.logical_and(*[...]) 不是您想要的。
另一种可能同样有效的方法是 np.all over an axis:
np.all([a for a in A[:3,:]], axis=0)
我刚刚做了一些快速测试,所以不能确定它是否总是相同,但值得检查(并且可能是时间)。
