如何模拟短路和开路

2024-10-01 17:24:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图检查二进制图像(模板)是否包含在另一个图像(源)中。为了做到这一点,我首先开始这样做:

(这是一个类似python的伪代码,但我对正确的技术比语言实现更感兴趣)

#this code runs once at startup
template_nonzero = count_nonzero(template)

#this code is run inside a function
mask = bitwise_and(template, source)
is_contained = count_nonzero(mask) == template_nonzero

然后我意识到我可以通过避免计数非零来加快速度:

mask = bitwise_and(template, source)
mask_against_template = bitwise_xor(template, mask)
is_contained = not mask_against_template.any()

这段代码比第一段代码快近3倍。我现在想知道opencv中是否存在短路和运算符,如果按位计算,它将返回true,对于所有白色像素都是true,或者在找到第一个false操作时返回false。这样,我就不必使用异或,甚至不必以位和的形式遍历整个图像。你知道吗

有什么想法吗?你知道吗

编辑:

我忘了说我甚至试过这段代码,但是使用xor比使用==:

mask = bitwise_and(template, source)
mask_against_template = template == mask
is_contained = mask_against_template.all()

Tags: and代码图像sourceiscountcodetemplate
1条回答
网友
1楼 · 发布于 2024-10-01 17:24:39

我最终找到了解决办法。我用python实现了短路和操作,结果比cv2.bitwise\u慢很多,然后是cv2.bitwise\uxor。但后来我用numba预编译了这个函数,结果得到了一个运行速度是cv2的4倍的函数。代码如下:

@numba.jit("b1(u1[:,:],u1[:,:])")
def is_template_in(template, image):
    for y in range(0, template.shape[0]):
        for x in range(0, template.shape[1]):
            if template[y][x] and not image[y][x]:
                return False
    return True

相关问题 更多 >

    热门问题