我正在尝试重现此example中的代码,但运行代码时出现异常:
import cv2
import numpy as np
def find_image(im, tpl):
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
np.logical_and(True, False)
npnd= np.logical_and(*[lookup[..., i] == tplsum[i] for i in range(D)])
possible_match = np.where(npnd)
# 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")
img1 = cv2.imread('c:/temp/1.png',0)
img2 = cv2.imread('c:/temp/3.png',0)
tplImg = cv2.imread('c:/temp/2.png',0)
find_image(img1, tplImg)
此行中发生异常:
npnd= np.logical_and(*[lookup[..., i] == tplsum[i] for i in range(D)])
它失败并显示以下异常消息:
C:\Python36-32>python.exe cvtest.py
Traceback (most recent call last):
File "cvtest.py", line 33, in <module>
find_image(img1, tplImg)
File "cvtest.py", line 19, in find_image
npnd= np.logical_and(*[lookup[..., i] == tplsum[i] for i in range(D)])
ValueError: invalid number of arguments
我做错了什么?如何修复它,使这段代码有效?
答案 0 :(得分:2)
错误是因为https://www.debian.org/mirror/list需要2个输入和一个可选out
- 参数。但是由于调用*[lookup[..., i] == tplsum[i] for i in range(D)]
,您有D
个参数。当D
为2时,一切正常,当它为3时你有一个Bug,当它有&#3}时2或&gt; 3你得到了你的例外。
>>> import numpy as np
>>> np.logical_and(*[[1]])
ValueError: invalid number of arguments
>>> np.logical_and(*[[1], [2]])
array([ True], dtype=bool)
>>> np.logical_and(*[[1], [2], np.array([1])])
array([1])
>>> np.logical_and(*[[1], [2], np.array([1]), 3])
ValueError: invalid number of arguments
这可以通过使用np.logical_and.reduce
来修复,np.logical_and.reduce([lookup[..., i] == tplsum[i] for i in range(D)])
采用任意数量的数组:
HttpTrigger