3D 矩阵切片的 2D 卷积

2D convolution of slices of 3D matrix

我正在尝试在 MATLAB 中对矩阵进行大量滚动求和。为了避免循环,我使用的 repmat to layer my 2D matrices into a 3D structure. However, now the fast convolution function conv2 can no longer be used for the accumulator. However, the N-dimensional convolution function (convn) 也不是我要找的,因为它确实涉及所有 3 个维度。我想要在每个切片和 return 3D 矩阵上进行 2D 卷积的东西。

在 2D 中平铺矩阵而不是在 3D 中将它们分层是行不通的,因为它会破坏卷积边缘情况。我可以在中间用零填充,但它开始变得有点乱。

换句话说,如果没有 for 循环,我该如何执行以下操作:

A = ones(5,5,5);
B = zeros(size(A));
for i = 1 : size(A, 3)
    B(:,:,i) = conv2(A(:,:,i), ones(2), 'same');
end

在此先感谢您的帮助!

您可以像这样使用一些 padding with zerosreshaping -

%// Store size parameters
[m,n,r] = size(A)  
[m1,n1] = size(kernel) 

%// Create a zeros padded version of the input array. We need to pad zeros at the end
%// rows and columns to replicate the convolutionoperation around those boundaries
Ap = zeros(m+m1-1,n+n1-1,r);
Ap(1:m,1:n,:) = A;

%// Reshape the padded version into a 3D array and apply conv2 on it and
%// reshape back to the original 3D array size
B_vect = reshape(conv2(reshape(Ap,size(Ap,1),[]),kernel,'same'),size(Ap))

%// Get rid of the padded rows and columns for the final output
B_vect = B_vect(1:m,1:n,:);

基本思想是将输入的 3D 数组重新整形为 2D 数组,然后对其应用 2D 卷积。填充需要额外的步骤,以便具有与边界周围 conv2 相同的行为。

convn 将使用 n 维矩阵和二维过滤器。只需:

A = ones(5,5,5);
B = convn(A, ones(2), 'same');