%% Upsample Image Using Transposed Convolution
% Convolve an image and then use transposed convolution to resize the convolved image to the same size as the original image.
% Import the image data and convert it to a dlarray.

X = imread('sherlock.jpg');
dlX = dlarray(single(X),'SSC');

% Display the image.

imshow(X)

% Initialize the convolutional filters and bias term. Specify an ungrouped convolution that applies a single filter to all three channels of the input data.

filterHeight = 10;
filterWidth = 10;
numChannelsPerGroup = 3;
numFiltersPerGroup = 1;
numGroups = 1;

weights = rand(filterHeight,filterWidth,numChannelsPerGroup,numFiltersPerGroup,numGroups);
bias = rand(numFiltersPerGroup*numGroups,1);

% Perform the convolution. Use a 'Stride' value of 2 and a 'DilationFactor' value of 2.

dlY = dlconv(dlX,weights,bias,'Stride',2,'DilationFactor',3);

% Display the convolved image.

Y = extractdata(dlY);
imshow(rescale(Y))

% Initialize the transposed convolutional filters and bias. Specify an ungrouped transposed convolution that applies three filters to the input. Use the same filter height and filter width as for the convolution operation.

numChannelsPerGroupTC = 1;
numFiltersPerGroupTC = 3;

weightsTC = rand(filterHeight,filterWidth,numFiltersPerGroupTC,numChannelsPerGroupTC,numGroups);
biasTC = rand(numFiltersPerGroupTC*numGroups,1);

% Perform the transposed convolution. Use the same stride and dilation factor as for the convolution operation.

dlZ = dltranspconv(dlY,weightsTC,biasTC,'Stride',2,'DilationFactor',3);

% Display the image after the transposed convolution.

Z = extractdata(dlZ);
imshow(rescale(Z))

% Compare the size of the original image, the convolved image, and the image after the transposed convolution.

sizeX = size(X)
sizeY = size(Y)
sizeZ = size(Z)

% The transposed convolution upsamples the convolved data to the size of the original input data.
% Copyright 2019 The MathWorks, Inc.