Search code examples
pythonnumpyscipyscientific-computing

Discrete Laplacian (del2 equivalent) in Python


I need the Python / Numpy equivalent of Matlab (Octave) discrete Laplacian operator (function) del2(). I tried couple Python solutions, none of which seem to match the output of del2. On Octave I have

image = [3 4 6 7; 8 9 10 11; 12 13 14 15;16 17 18 19]
del2(image)

this gives the result

   0.25000  -0.25000  -0.25000  -0.75000
  -0.25000  -0.25000   0.00000   0.00000
   0.00000   0.00000   0.00000   0.00000
   0.25000   0.25000   0.00000   0.00000

On Python I tried

import numpy as np
from scipy import ndimage
import scipy.ndimage.filters
    
image =  np.array([[ 3,  4,  6,  7],
                   [ 8,  9, 10, 11],
                   [12, 13, 14, 15],
                   [16, 17, 18, 19]])
stencil = np.array([[0,  1, 0],
                    [1, -4, 1],
                    [0,  1, 0]])
print ndimage.convolve(image, stencil, mode='wrap')

which gives the result

[[ 23  19  15  11]
 [  3  -1   0  -4]
 [  4   0   0  -4]
 [-13 -17 -16 -20]]

I also tried

scipy.ndimage.filters.laplace(image)

That gives the result

[[ 6  6  3  3]
 [ 0 -1  0 -1]
 [ 1  0  0 -1]
 [-3 -4 -4 -5]]

So none of the outputs seem to match eachother. Octave code del2.m suggests that it is a Laplacian operator. Am I missing something?


Solution

  • Maybe you are looking for scipy.ndimage.filters.laplace() (which in 2023 is scipy.ndimage.laplace).