如何在opencv中模拟短路
How to simulate short circuit and in opencv
我正在尝试检查二进制图像(模板)是否包含在另一个图像(源)中。为此,我首先开始做这样的事情:
(它是一个类似于 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
然后我意识到我可以通过避免 count_nonzero:
来加快速度
mask = bitwise_and(template, source)
mask_against_template = bitwise_xor(template, mask)
is_contained = not mask_against_template.any()
这段代码比第一个代码快了将近 3 倍。我现在想知道 opencv 中是否存在短路和运算符这样的东西,如果 bitwise_and 对所有白色像素为真或在发现第一个错误操作时为假,则 return 为真。这样我就不必在 bitwise_and.
中对整个图像使用 xor 甚至 运行
有什么想法吗?
编辑:
我忘了说我什至试过这段代码,但是使用 xor 比使用 ==:
快一点
mask = bitwise_and(template, source)
mask_against_template = template == mask
is_contained = mask_against_template.all()
我最终找到了解决方案。我在 python 中实现了短路和操作,结果比 cv2.bitwise_and 后跟 cv2.bitwise_xor 慢很多。但是后来我使用 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
我正在尝试检查二进制图像(模板)是否包含在另一个图像(源)中。为此,我首先开始做这样的事情:
(它是一个类似于 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
然后我意识到我可以通过避免 count_nonzero:
来加快速度mask = bitwise_and(template, source)
mask_against_template = bitwise_xor(template, mask)
is_contained = not mask_against_template.any()
这段代码比第一个代码快了将近 3 倍。我现在想知道 opencv 中是否存在短路和运算符这样的东西,如果 bitwise_and 对所有白色像素为真或在发现第一个错误操作时为假,则 return 为真。这样我就不必在 bitwise_and.
中对整个图像使用 xor 甚至 运行有什么想法吗?
编辑:
我忘了说我什至试过这段代码,但是使用 xor 比使用 ==:
快一点mask = bitwise_and(template, source)
mask_against_template = template == mask
is_contained = mask_against_template.all()
我最终找到了解决方案。我在 python 中实现了短路和操作,结果比 cv2.bitwise_and 后跟 cv2.bitwise_xor 慢很多。但是后来我使用 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