use*_*323 4 python arrays opencv numpy
我是使用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
这是有效的,但似乎并不优雅或高效.我希望有更快的解决方案......
任何建议都是最受欢迎的
这是一个矢量化代码的好地方,用于解释和演示.
#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 <= It不是Mt < 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编译器.
| 归档时间: | 
 | 
| 查看次数: | 1100 次 | 
| 最近记录: |