【问题标题】:Comparing two OpenCV images/2D Numpy arrays比较两个 OpenCV 图像/2D Numpy 数组
【发布时间】:2013-09-17 05:16:08
【问题描述】:

我是使用 OpenCV、Python 和 Numpy 的新手,但现在已经是 Java、C++、C 程序员一段时间了。

我正在实现一个 sigma-delta 背景检测器,它执行以下操作:

让 i1 成为第一张图片,让 i2 成为第二张图片

    for each pixel:
    if i1(x,y) > i2(x,y), then i2(x,y) = i2(x,y) + 1
    if i1(x,y) < i2(x,y), then i2(x,y) = i2(x,y) - 1

我基本上是在尝试遍历 2D 图像数组并将像素值与另一个图像进行比较,但我正在努力使用 for 循环来处理 numpy 数组。我尝试使用嵌套的 for 循环,但我收到一条错误消息,提示我无法访问该数组的元素。

编辑:

for x in range (width):
    for y in range (height):
        if Mt [x,y] > It[x,y]:
            Mt [x,y] = Mt[x,y]+1
        elif Mt [x,y] < It[x,y]:
            Mt [x,y] = Mt[x,y]-1

这是有效的,但看起来不是很优雅或高效。我希望有一个更快的解决方案...

欢迎提出建议

【问题讨论】:

  • 1.您应该发布实际代码,并附上一些上下文 2。您应该发布错误消息

标签: python arrays opencv numpy


【解决方案1】:

这是一个矢量化代码的好地方,用于解释和演示。

#Generate two random arrays, shape must be the same
>>> Mt = np.random.rand(2,2)
>>> It = np.random.rand(2,2)
>>> Mt
array([[ 0.47961753,  0.74107574],
       [ 0.94540074,  0.05287875]])
>>> It
array([[ 0.86232671,  0.45408798],
       [ 0.99468912,  0.87005204]])

#Create a mask based on some condition
>>> mask = Mt > It
>>> mask
array([[False,  True],
       [False, False]], dtype=bool)

#Update in place
>>> Mt[mask]+=1
>>> Mt[~mask]-=1  #Numpy logical not
>>> Mt
array([[-0.52038247,  1.74107574],
       [-0.05459926, -0.94712125]])

您可能需要创建第二个掩码,因为当前减法掩码是 Mt &lt;= It 而不是 Mt &lt; It,但这是展示逻辑不的好地方。


要完全重现您的代码,请改用此代码:

Mt[Mt > It]+=1
Mt[Mt < It]-=1  

因为我对这些东西感兴趣:

 def looper(Mt,It):
     for x in range (Mt.shape[0]):
         for y in range (Mt.shape[1]):
             if Mt [x,y] > It[x,y]:
                Mt [x,y] +=1
             elif Mt [x,y] < It[x,y]:
                Mt [x,y] -=1

nlooper = autojit(looper)

Mt = np.random.rand(500,500)
It = np.random.rand(500,500)

%timeit looper(Mt,It)
1 loops, best of 3: 531 ms per loop

%timeit Mt[Mt > It]+=1;Mt[Mt < It]-=1
100 loops, best of 3: 2.27 ms per loop

%timeit nlooper(Mt,It)
1 loops, best of 3: 308 µs per loop

autojit 是来自numba 模块的python/numpy 的JIT 编译器。

【讨论】:

  • 这正是我想要的。我希望将其移植到 Raspberry Pi,因此速度非常重要。面膜效果很好。感谢@Ophion 的快速回复
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
  • 1970-01-01
  • 2013-04-20
  • 2019-02-06
  • 2017-01-18
  • 1970-01-01
相关资源
最近更新 更多