3

I'm translating Matlab code into Python code and I need your help to know how to translate this line in Matlab.

Matrix =  convn(Matrix2, ones(x,x,x)/x^3, 'same');

I'm asking, because conv2 in Matlab, doesn't have a direct equivalent in Python and I had to use the solution proposed here : Is there a Python equivalent of MATLAB's conv2 function?

where they rotate the image :

def conv2(x, y, mode='same')
return np.rot90(convolve2d(np.rot90(x, 2), np.rot90(y, 2), mode=mode), 

I thus assume that we must do something like this too, but in 3D, hence why I'm asking for your help!

Thanks!

Community
  • 1
  • 1
Xavier-rp
  • 133
  • 1
  • 7
  • 2
    Did you look into `fftconvolve`? http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.fftconvolve.html#scipy.signal.fftconvolve – Suever Aug 22 '16 at 16:06
  • I tried to use fftconvolve in another context, and, although it was quick, gave me different results (unless rotated like in the example above) and some kind of « zero artifacts » which were numbers close to zero instead of actual zeros. This led to errors later on since I used these values in exponentials. But I'll take a look again! – Xavier-rp Aug 22 '16 at 22:41
  • There's a `np.convolve` with the same `mode` options. Though it may be more like `conv` or `conv2`. – hpaulj Aug 22 '16 at 23:38

1 Answers1

0

Well, I have two crazy ideas.

One is we can directly use MATLAB’s ‘convn’ in Python. By doing this, open a MATLAB server in Python with ‘eng = matlab.engine.connect_matlab()’.

Now, we can use everything that is belong to MATLAB.

Matrix = eng.convn(Matrix2, ones(x,x,x)/x^3, 'same')

In fact, we can run entire old code in Python with this method, when these codes end with a matrix with small dimensions. We translate it to ‘Numpy’ with

‘numpyArray =np.array(MATLAB_array,dtype=np.XXX)’.

Be carefully. If dimensions of your matrix are large, this translation will be slow.

Another crazy idea is to use ‘tf.nn.conv3d’ in ‘Tensorflow’. The side effect is indirect. We have to build a session to run it with ‘sess = tf.Session()’.

I am not a programmer, but I think that the MATLB is unwilling to be replaced by Python. If you have down a lot of work in MATLAB, it may be hard to translate the code.

Blue Bird
  • 318
  • 2
  • 9