1

I have an application where I have to process 1000's of 2D arrays. The result of the processed array is based on half of a Kings Move neighborhood in the original array. I'm trying to avoid loops if I can due to speed considerations. So, here is an example Numpy Array:

array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.,  1.,  1.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  5.,  5.,  5.,  5.,  0.,  0.,  0.],
       [ 0.,  1.,  5.,  5.,  1.,  1.,  1.,  1.,  1.,  0.,  0.],
       [ 5.,  5.,  5.,  5.,  1.,  5.,  1.,  1.,  1.,  1.,  0.],
       [ 1.,  1.,  1.,  5.,  1.,  1.,  5.,  5.,  1.,  1.,  0.],
       [ 5.,  1.,  5.,  1.,  1.,  5.,  5.,  5.,  1.,  5.,  0.],
       [ 0.,  5.,  1.,  5.,  1.,  1.,  1.,  1.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  1.,  1.,  1.,  1.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  5.,  5.,  5.,  0.,  0.,  0.,  0.]])

At each element, I want the sum of the cell right above it, the upper right diagonal element, the cell to the immediate right and the lower diagonal. So, using the element at [6][0] I would want to sum 1 + 1 + 1 + 5.

Of course, I also have to handle the edge cases where one of the 4 cells is not there. I have started with the padded zeros on top and far right to manage some of that but I'm stuck right now. Any advice would be much appreciated!

1
  • I've suggested a couple of improvements for a similar problem in codereview.stackexchange.com/a/149176/27783; you might also find a lot of convolve2d suggestions here on SO. Commented Dec 14, 2016 at 23:44

1 Answer 1

1

What you're doing can be viewed as performing a convolution with a particular convolution kernel. Here's a solution using the scipy convolve2d function:

import numpy as np
import scipy as sp
import scipy.signal

x = np.random.randint(5,size=(10,10))

kernel = np.array([[0,1,1],[0,0,1],[0,0,1]])
kernel = np.fliplr(np.flipud(kernel))

check = sp.signal.convolve2d(x,kernel,mode='same')

print x
print check
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, this is exactly what I was looking for! Your approach to create the kernel in the form that I can see where it starts and it's mirror image applied was very helpful in understanding the process.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.