MATLAB: Using convn with pictures and kernel.

cellcellfunconvn

I have an image with this dimension 6×6 (M,N). where the third dimension is the number of picture 6x6x20.
I will convolve each image with 2 mask 3x3x2 (M,N,#mask)
first I want to transform my images to cells without use a bucle function, I think is possible with "num2cell", but I don't have enought experience using this function. something like
Image_Cell = {6x6x1;
6x6x2;
.
.
6x6x20};
size(Image_Cell)
ans =
20 1
Finally, convolve each mask with each picture. and I know how to do it with for function. But I would like to not depend of this because would be slower. I don't know if I can use "cellfun".
% Image Mask1 Image Mask2
Convolution = {convn(6x6x1,3x3x1,'valid'),convn(6x6x1,3x3x2,'valid');
convn(6x6x2,3x3x1,'valid'),convn(6x6x2,3x3x2,'valid');
convn(6x6x3,3x3x1,'valid'),convn(6x6x3,3x3x2,'valid');
.
.
convn(6x6x20,3x3x1,'valid'),convn(6x6x20,3x3x2,'valid')};
size(Convolution)
ans =
20 2

Best Answer

It would be pointless to convert your 3D arrays into cell arrays of 2D arrays. You would just be storing the same information but using more memory to do so. The code to apply the convolution would be the same: a loop. In addition since you want to do a 2D convolution, you'd be using conv2, not convn.
%Images: a M x N x NumImages matrix
%Masks: a P x Q x NumMasks matrix
result = zeros(size(Images, 1) - size(Masks, 1) + 1, size(Images, 2) - size(Masks, 2) + 1, size(Images, 3), size(Masks, 3)); %4D matrix for output
for imgidx = 1:size(Images, 3)
for maskidx = 1:size(Masks, 3)
result(:, :, imgidx, maskidx) = conv2(Images(:, :, Imgidx), Masks(:, :, Maskidx), 'valid');
end
end