Calculate average round cell value from each 2D array cell

I am try to practice the leetcode and hit the following question 'image smooth'. Basically the question is to calculate average the around cell value from a 2D array. I have following code. But if there is better way to do it at least better performance?

def imageSmoother(M):
"""
:type M: List[List[int]]
:rtype: List[List[int]]
"""
import numpy as np
from math import floor
m_np = np.array(M)
tol_r, tol_c = m_np.shape
mx = np.zeros(shape=(tol_r, tol_c), dtype=int)
for r in range(0, tol_r):
for c in range(0, tol_c):
row = slice(max(0, r-1), min(tol_r, r + 2))
col = slice(max(0, c-1), min(tol_c, c + 2))
total = m_np[row, col].sum()
x, y = m_np[row, col].shape
mx[r, c] = floor(total/(x * y))
return mx.tolist()

• Are you trying to re-invent the wheel? If not, check out convolve docs.scipy.org/doc/numpy/reference/generated/… – Oscar Smith Dec 3 '18 at 23:51
• nice suggestion, never know numpy has that but we are allowed to provide use during whiteboard coding? – jacobcan118 Dec 3 '18 at 23:54
• scipy.ndimage.convolve is designed for exactly this kind of problem. To handle the edges and corners you'll want to pass mode='constant', cval=0 and adjust the averages along the edges. – Gareth Rees Dec 4 '18 at 11:08
• @jacobcan118: Whether or not that would be allowed in a coding interview is entirely up to the interviewer. One possible chain of events would be you saying, "Use scipy.ndimage.convolve", them saying "Yes, in the real world that would be the best way to do it (no need to spend time reinventing the wheel), but if you had to write it yourself how would you do it?" to which you would answer something like the code you posted here. – Graipher Dec 5 '18 at 17:52