Comparison of two OpenCV / 2D Numpy images

I am new to using OpenCV, Python and Numpy, but have been a Java, C ++, C programmer for a while.

I implement a sigma-delta-background detector that does the following:

let i1 be the first image, i2 be the second image

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 

I'm basically trying to iterate through an array of 2D images and compare the pixel value with another image, but I'm struggling to work with numpy arrays that use for loops. I tried using a nested loop, but I get an error that I cannot access the elements of this array.

Edit:

 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 

It works, but does not seem very elegant or effective. I hope for a faster solution ...

Any suggestions would be most welcome.

+4
source share
1 answer

This is a great place to vectorize code, for explanation and demonstration.

 #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]]) 

You probably need to create a second mask, since the subtraction mask is currently Mt <= It not Mt < It , however this was a good place to demonstrate a logical not.


To reproduce your code exactly use this:

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

Because I am interested in these things:

  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 is the JIT compiler for python / numpy from the numba module.

+6
source

Source: https://habr.com/ru/post/1501915/


All Articles