简体   繁体   中英

2D convolution of slices of 3D matrix

I'm trying to do a bunch of rolling sums over matrices in MATLAB. In order to avoid loops I've used 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 ) is not what I'm looking for either as it literally convolves all 3 dimensions. I want something that will do a 2D convolution on each slice and return a 3D matrix.

Tiling the matrices in 2D instead of layering them in 3D won't work because it will corrupt the convolution edge cases. I could pad with zeros in between but then it starts getting kind of messy.

In other words, without a for-loop, how can I perform the following:

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

Thanks in advance for the help!

convn will work with an n-dimensional matrix and a 2-dimensional filter. Simply:

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

You can use some padding with zeros and reshaping like so -

%// 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,:);

The basic idea is to reshape the input 3D array into a 2D array and then apply the 2D convolution on it. Extra step is needed with padding so as to have the same behavior as you would see with conv2 around the boundaries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM