Compute neighborhood product for each cell in a matrix with numpy / scipy

I am trying to implement an image processing algorithm that involves calculating the product of a 4-adjacent neighborhood for each cell. That is, calculate a new matrix Y for X, where y[i, j] = x[i-1, j] * x[i, j-1] * x[i+1, j] * x[i, j+1] . Unsent neighbors should be ignored.

Now I can only think about it: use scipy.ndimage.filters.correlate and pass the weights with zeros and one 1 to get four matrices, each of which contains a neighbor for each cell in a direction, for example, passing through weight = [[0, 0, 0], [1, 0, 0], [1, 1]] , and I get a[i, j] = x[i-1, j] , and with other weights I can get b[i, j] = x[i, j-1] , c[i, j] = x[i+1, j] , d[i, j] = x[i, j+1] . Then I use np.multiply to calculate the product of these four matrices.

However, this approach is too slow, and I can not ignore the boundaries. Is there any other way to do this with numpy / scipy, so I don't need to resort to loops?

+5
source share
2 answers

You will need to write the edges separately, but this does what you need for the central part of your array, and is probably noticeably faster than the correlation:

 y = np.empty_like(x) y[1:-1, 1:-1] = x[1:-1, 1:-1] y[1:-1, 1:-1] *= x[:-2, 1:-1] y[1:-1, 1:-1] *= x[2:, 1:-1] y[1:-1, 1:-1] *= x[1:-1, :-2] y[1:-1, 1:-1] *= x[1:-1, 2:] 
+3
source

I think this fits better with what you are asking:

 import numpy as np x = np.array([ [1, 2, 3, 4, 5], [6, 7, 8, 9, 1], [2, 3, 4, 5, 6], [7, 8, 9, 1, 2] ]) y = np.ones_like(x) y[+1:, :] *= x[:-1, :] y[:-1, :] *= x[+1:, :] y[:, +1:] *= x[:, :-1] y[:, :-1] *= x[:, +1:] y #>>> array([[ 12, 21, 64, 135, 4], #>>> [ 14, 288, 756, 160, 270], #>>> [ 126, 448, 1080, 216, 10], #>>> [ 16, 189, 32, 90, 6]]) 

Please note that the first *= may be the destination if you need extra speed.

+3
source

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


All Articles