PythonまたはそのモジュールのいずれかにMATLABのconv2関数と同等のものがありますか?具体的にはconv2(A, B, 'same')
、MATLABと同じ計算を行うものに興味があります。
12808 次
4 に答える
9
scipy.signal.convolve2d
他の回答はすでに同等のものとして言及していますが、を使用すると結果が異なることがわかりましたmode='same'
。
Matlabのconv2
結果、画像の下部と右側にアーティファクトが発生しますが、画像scipy.signal.convolve2d
の上部と左側にも同じアーティファクトがあります。
動作を示すプロットについては、次のリンクを参照してください(画像を直接投稿するには評判が不十分です)。
次のラッパーはあまり効率的ではないかもしれませんが、私の場合、入力配列と出力配列の両方をそれぞれ180度回転させることで問題を解決しました。
import numpy as np
from scipy.signal import convolve2d
def conv2(x, y, mode='same'):
return np.rot90(convolve2d(np.rot90(x, 2), np.rot90(y, 2), mode=mode), 2)
于 2016-07-13T15:27:15.583 に答える
5
scipy.signal.convolve2dがあなたが探しているもののように見えます。
于 2010-09-16T23:25:30.390 に答える
1
scipy.ndimage.convolve
n次元でそれを行います。
于 2010-09-16T21:55:38.327 に答える
1
Matlabのconv2の結果を再現するには、シングルトン以外の次元ごとにオフセットを指定する必要があります。'same'オプションのみをサポートする単純な実装は、次のように作成できます。
import numpy as np
from scipy.ndimage.filters import convolve
def conv2(x,y,mode='same'):
"""
Emulate the function conv2 from Mathworks.
Usage:
z = conv2(x,y,mode='same')
TODO:
- Support other modes than 'same' (see conv2.m)
"""
if not(mode == 'same'):
raise Exception("Mode not supported")
# Add singleton dimensions
if (len(x.shape) < len(y.shape)):
dim = x.shape
for i in range(len(x.shape),len(y.shape)):
dim = (1,) + dim
x = x.reshape(dim)
elif (len(y.shape) < len(x.shape)):
dim = y.shape
for i in range(len(y.shape),len(x.shape)):
dim = (1,) + dim
y = y.reshape(dim)
origin = ()
# Apparently, the origin must be set in a special way to reproduce
# the results of scipy.signal.convolve and Matlab
for i in range(len(x.shape)):
if ( (x.shape[i] - y.shape[i]) % 2 == 0 and
x.shape[i] > 1 and
y.shape[i] > 1):
origin = origin + (-1,)
else:
origin = origin + (0,)
z = convolve(x,y, mode='constant', origin=origin)
return z
于 2015-10-14T12:38:07.150 に答える