%% Create Mini-Batches Using Custom Preprocessing Function
% Preprocess data using a minibatchqueue with a custom mini-batch preprocessing function. The custom function rescales the incoming image data between 0 and 1 and calculates the average image.
% Unzip the data and create a datastore.

unzip("MerchData.zip");
imds = imageDatastore("MerchData", ...
    "IncludeSubfolders",true, ...
    "LabelSource",'foldernames'); 

%
% Create a minibatchqueue that preprocesses data using the custom function preprocessMiniBatch defined at the end of this example. The custom function concatenates the image data into a numeric array,  rescales the image between 0 and 1, and calculates the average of the batch of images. The function returns the rescaled batch of images and the average image.  Set the number of outputs to 2, to match the number of outputs of the function.

mbq = minibatchqueue(imds,2,...
    'MiniBatchSize',16,...
    'MiniBatchFcn',@preprocessMiniBatch,...
    'OutputAsDlarray',0)

% Obtain a mini-batch and display the average of the images in the mini-batch.

[X,averageImage] = next(mbq);
imshow(averageImage)

%

function [X,averageImage] = preprocessMiniBatch(XCell)
    X = cat(4,XCell{:});
    
    X = rescale(X,"InputMin",0,"InputMax",255);
    averageImage = mean(X,4);

end

% Copyright 2020 The MathWorks, Inc.