Conv matlab in python

Conv в Matlab в Python

Я переводил код Matlab в код Python, и мне нужна ваша помощь, чтобы знать, как перевести эту строку в Matlab.

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

Я спрашиваю, потому что conv2 в Matlab не имеет прямого эквивалента в Python, и мне пришлось использовать предлагаемое здесь решение: Есть ли эквивалент Python для конвекса MATLAB функция? где они поворачивают изображение:

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

Таким образом, я предполагаю, что мы должны делать что-то подобное, но в 3D, поэтому я прошу вас о помощи! Спасибо!

Я попытался использовать fftconvolve в другом контексте и, хотя это было быстро, дал мне другие результаты (если их не повернуть, как в приведенном выше примере) и что-то вроде «нулевых артефактов», которые были числами, близкими к нулю, а не фактическими нулями. Это привело к ошибкам позже, так как я использовал эти значения в экспоненте. Но я еще раз посмотрю!

Там есть np.convolve с np.convolve же параметрами mode . Хотя это может быть больше похоже на conv или conv2 .

1 ответ

Ну, у меня две сумасшедшие идеи.

Один из них заключается в том, что мы можем напрямую использовать конкатенацию MATLABs в Python. Делая это, откройте сервер MATLAB в Python с помощью ‘eng = matlab.engine.connect_matlab().

Читайте также:  Java connect socket to server

Теперь мы можем использовать все, что принадлежит MATLAB.

Матрица = eng.convn(Матрица2, единицы (x, x, x)/x ^ 3, ‘same’)

Фактически, мы можем запустить весь старый код в Python с помощью этого метода, когда эти коды заканчиваются матрицей с малыми размерами. Мы переводим его в «Numpy with

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

Будьте осторожны. Если размеры вашей матрицы велики, этот перевод будет медленным.

Еще одна сумасшедшая идея — использовать ‘tf.nn.conv3d в’ Tensorflow. Побочный эффект непрямой. Мы должны построить сеанс, чтобы запустить его с помощью sess = tf.Session().

Я не программист, но я думаю, что MATLB не хочет быть замененным на Python. Если у вас много работы в MATLAB, может быть сложно перевести код.

Источник

Convolution in MATLAB, NumPy, and SciPy

How to compute convolution using numerical software libraries?

The Convolution Series

  1. Definition of convolution and intuition behind it
  2. Mathematical properties of convolution
  3. Convolution property of Fourier, Laplace, and z-transforms
  4. Identity element of the convolution
  5. Star notation of the convolution
  6. Circular vs. linear convolution
  7. Fast convolution
  8. Convolution vs. correlation
  9. Convolution in MATLAB, NumPy, and SciPy
  10. Deconvolution: Inverse convolution
  11. Convolution in probability: Sum of independent random variables

Most often we won’t be implementing convolution every time we need to use it. Therefore, it is important to know functions from numerical software libraries we can use.

The most popular implementation of the convolution are conv from Matlab, convolve from NumPy, and convolve from SciPy. I won’t be describing any C/C++ convolution implementations here.

3 Modes of Convolution

Before we dive into the specific functions, it is important to understand 3 different ‘modes’ the convolution can be calculated with.

We will observe their effect using the following signals: x [ n ] x[n] x [ n ]

Figure 1. x [ n ] x[n] x [ n ] .

Figure 2. y [ n ] y[n] y [ n ] .

Full

‘Full’ is the mathematical implementation of convolution. Having signals of length M M M and N N N , the ‘full’ mode returns a signal of length M + N − 1 M + N — 1 M + N − 1 . At points where signals do not overlap, they are padded with zeros.

Figure 3. ‘Full’ mode of the convolution.

This is the default option for Matlab, NumPy, and SciPy.

Valid

‘Valid’ mode does not use zero padding at all. The output is calculated only at positions where signals overlap completely. The result is a very short vector of length max ⁡ ( M , N ) − min ⁡ ( M , N ) + 1 \max(M, N) — \min(M, N) + 1 max ( M , N ) − min ( M , N ) + 1 .

Figure 4. ‘Valid’ mode of the convolution.

Note that using this mode of convolution shrinks the output signal with each application [6].

Same

‘Same’ acts as an intermediate level between ‘full’ and ‘valid’; it crops the middle part out of the ‘full’ mode. Its length is equal to the length of the longer signal (NumPy, SciPy) or the first signal given (Matlab). This approach comes in handy when we want to keep the size of the convolution output constant.

Figure 5. ‘Same’ mode of the convolution.

Convolution Functions

Knowing the 3 modes, we can present now convolution functions of different numerical software libraries.

NumPy

numpy.convolve has the following signature

output = numpy.convolve(x, y, mode='full')

x and y are 1-D-arrays and mode is a string containing the convolution mode name.

SciPy

scipy.signal.convolve has the following signature

output = scipy.signal.convolve(x, y, mode='full', method='auto')

x and y are N-D-arrays, mode is a string containing the convolution mode name, and method can be direct (evaluation according to the convolution definition), fft (equivalent to the usage of scipy.signal.fftconvolve , i.e., the fast convolution algorithm), or auto (let the software decide).

FFT convolution (fast convolution) is recommended for long signals of similar size.

SciPy has another convolution function, namely, oaconvolve . It lets the user pick the axes to compute convolution over. It uses the overlap-add scheme and, thus, is recommended for long signals of significanlty different sizes.

oaconvolve and fftconvolve have the same signature: they take two multidimensional input signals, mode argument, and axes argument to compute the convolution over (an integer, an array, or None to use all axes).

scipy.signal.fftconvolve(x, y, mode='full', axes=None) scipy.signal.oaconvolve(x, y, mode='full', axes=None)

Matlab

Matlab’s conv has the following signature

output = conv(x, y, shape) % shape is 'full' if not explicitly given

x and y are 1-D, row or column vectors. For 2-D convolution, one may use conv2 function, and for N-D convolution, there is convn function.

Summary

In this article, we have discussed 3 modes of convolution: full , valid , and same and the implementations of convolution in NumPy, SciPy, and Matlab.

Check out the references below for more details.

Источник

Matlab’s conv() in Python

conv to calculate convolution in matlab. He’s familiar with Gaussian filters and stuff.

numpy.convolve

Matlab’s conv is almost identical to numpy.convolve.

Become. The same is true that the shape is either ‘full’ ‘same’ or ‘valid’

However, when the lengths of u and v are both even numbers and ‘same’, it seems that the range returned is different by one. Well, in filtering, v is mostly symmetrical and odd in length, so I don’t think it matters too much.

When at least one of the lengths of you and v is odd

x=1:10; y=[0,1,0.5]; conv(x,y,'full') conv(x,y,'same') conv(x,y,'valid') 
ans = 0 1.0000 2.5000 4.0000 5.5000 7.0000 8.5000 10.0000 11.5000 13.0000 14.5000 5.0000 ans = 1.0000 2.5000 4.0000 5.5000 7.0000 8.5000 10.0000 11.5000 13.0000 14.5000 ans = 2.5000 4.0000 5.5000 7.0000 8.5000 10.0000 11.5000 13.0000 
import numpy as np x = range(1, 11) y = (0, 1, 0.5) print(np.convolve(x, y, 'full')) print(np.convolve(x, y, 'same')) print(np.convolve(x, y, 'valid')) 
[ 0. 1. 2.5 4. 5.5 7. 8.5 10. 11.5 13. 14.5 5. ] [ 1. 2.5 4. 5.5 7. 8.5 10. 11.5 13. 14.5] [ 2.5 4. 5.5 7. 8.5 10. 11.5 13. ] 

When the lengths of you and v are both even

x=1:9; y=[0,1,0.5,0.1]; conv(x,y,'full') conv(x,y,'same') conv(x,y,'valid') 
ans = 0 1.0000 2.5000 4.1000 5.7000 7.3000 8.9000 10.5000 12.1000 13.7000 5.3000 0.9000 ans = 2.5000 4.1000 5.7000 7.3000 8.9000 10.5000 12.1000 13.7000 5.3000 ans = 4.1000 5.7000 7.3000 8.9000 10.5000 12.1000 
x = range(1, 10) y = (0, 1, 0.5,0.1) print(np.convolve(x, y, 'full')) print(np.convolve(x, y, 'same')) print(np.convolve(x, y, 'valid')) 
[ 0. 1. 2.5 4.1 5.7 7.3 8.9 10.5 12.1 13.7 5.3 0.9] [ 1. 2.5 4.1 5.7 7.3 8.9 10.5 12.1 13.7] [ 4.1 5.7 7.3 8.9 10.5 12.1] 

When same, Matlab has one longer output

Источник

Оцените статью