gpt4 book ai didi

python - numpy.logic_and 代码示例中的解释

转载 作者:行者123 更新时间:2023-12-01 03:14:02 25 4
gpt4 key购买 nike

我正在尝试重现此代码 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

我做错了什么?如何修复它以使此代码正常工作?

最佳答案

错误是因为np.logical_and采用 2 个输入和一个可选的输出参数。然而,由于调用 *[lookup[..., i] == tplsum[i] for i in range(D)] 你有 D 参数。当D为2时一切正常,当它为3时你有一个Bug,当它为<2或>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.logic_and.reduce 来修复,它接受任意数量的数组:

np.logical_and.reduce([lookup[..., i] == tplsum[i] for i in range(D)])

关于python - numpy.logic_and 代码示例中的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42635948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com