Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 715
BBSysDyn Avatar asked Jan 14 '11 14:01

BBSysDyn


2 Answers

Maybe you are looking for scipy.ndimage.filters.laplace().

like image 125
Sven Marnach Avatar answered Sep 18 '22 18:09

Sven Marnach


You can use convolve to calculate the laplacian by convolving the array with the appropriate stencil:

from scipy.ndimage import convolve
stencil= (1.0/(12.0*dL*dL))*np.array(
        [[0,0,-1,0,0], 
         [0,0,16,0,0], 
         [-1,16,-60,16,-1], 
         [0,0,16,0,0], 
         [0,0,-1,0,0]])
convolve(e2, stencil, mode='wrap')
like image 40
2daaa Avatar answered Sep 21 '22 18:09

2daaa