虽然一般来说,opencv (cv2) 的新 python 绑定(bind)很漂亮,但“掩码”似乎无法正常工作——除非我真的弄错了:
例如“cv2.add”在没有掩码的情况下仍然可以正常工作:
import cv2
a = ones((2,2,3), dtype=uint8)
cv2.add(a,a)
正确给出
array([[[2, 2, 2],
[2, 2, 2]],
[[2, 2, 2],
[2, 2, 2]]], dtype=uint8)
但是当你添加一个掩码(并且输出数组“b” - 由于某种原因需要它也没有分配)你会得到一个随机结果,即当你多次运行命令时结果会改变
myMask = zeros(a.shape[0:2], dtype = uint8)
mask[1,1] = 255
b = zeros(a.shape)
cv2.add(a,a,b,myMask)
cv2.add(a,a,b,myMask)
在我的机器上(Win7、32位、Python 2.7、opencv 2.3.1)
In [34]: cv2.add(a,a,b,myMask)
Out[34]:
array([[[ 26, 0, 143],
[ 5, 216, 245]],
[[156, 5, 104],
[ 2, 2, 2]]], dtype=uint8)
In [35]: cv2.add(a,a,b,myMask)
Out[35]:
array([[[35, 0, 0],
[ 0, 3, 0]],
[[ 0, 0, 3],
[ 2, 2, 2]]], dtype=uint8)
...以及下一次试用的新内容。现在要么我遇到严重错误,要么 cv2 绑定(bind)存在严重问题。
有什么建议吗?
最佳答案
这是个有趣的问题。我看到了同样的问题。我发布了一个错误并得到了回复。 http://code.opencv.org/issues/1748
解决方法很简单。 dst 数组在创建时未定义,操作仅更改目标数组像素 p,其中 mask(p)!=0。
所以唯一可行的机制是在添加之前预制作 dst。 即
dst = np.zeros(...)
dst = cv2.add(a, a, dst=dst, mask=mask)
下一个版本将清除 cv2.add、cv2.subtract、cv2.bitwise_and/or/xor 等操作中新创建的图像 - 因此它可以正常工作。
我的代码如下:
import cv2
import numpy as np
import time
a = np.ones((2,2,3), dtype=np.uint8)
print "simple add"
t = time.time()
for i in range(10000):
b = cv2.add(a,a)
print "%5.4f seconds" % (time.time()-t)
print b
print "\nnumpy add"
t = time.time()
for i in range(10000):
b = a+a
print "%5.4f seconds" % (time.time()-t)
print b
# make mask same dimensions but 1 byte deep(not three)
mask = np.zeros(a.shape[:-1], dtype=np.uint8)
mask[1,1] = 255
print "\nmask", mask.shape
print mask
print "\nmasked add - uninitialised"
t = time.time()
for i in range(10000):
b = cv2.add(a,a,mask=mask)
print "%5.4f seconds" % (time.time()-t)
print b
print "uninitialised entries are unmodified - so random.\n Inconsistent when run more than once."
print "same calc a second time..."
b = cv2.add(a,a,mask=mask)
print b
print "\nmasked add - using preinitialised dst"
t = time.time()
b = a.copy()
for i in range(10000):
b = cv2.add(a,a,b,mask=mask)
print "%5.4f seconds" % (time.time()-t)
print b
print "Consistent when run more than once."
print "same calc a second time..."
b = a.copy()
b = cv2.add(a,a,b,mask=mask)
print b
仅供引用:计时(10k 次重复):
cv2.add - no mask 0.0120 seconds
cv2.add - with mask 0.0160 seconds
np.add 0.0190 seconds
cv2.add - uninitialised mask 0.0220 seconds
仅供引用:按照此处的说明提交错误: http://code.opencv.org/projects/OpenCV/wiki/WikiStart
关于python - python opencv cv2 中的掩码不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8464800/