function img = imgPreprocessing(path)
%--------------------------------------------------------------------------
% Introduction to Artificial Intelligence (DPEM306)
% Lab material for Assignment 03
%--------------------------------------------------------------------------
%
% The function imgPreprocessing() converts an image (.jpg or .png) in a
% format suitable to be fed to the trained ANN.
%
% INPUT:
%    path :  [character array], folder path and filename of the image  
%                               (including extension),
%                               i.e. 'D:\myfiles\assignment03\img4.jpg'
% OUTPUT:
%    img  :  [array 784x1], array in format suitable to be fed to the
%                           trained ANN
%

image = imread(path);
img_bw = im2bw(mat2gray(image));
% figure; imagesc(img_bw); colormap(gray);

cc = bwconncomp(img_bw);
stats = regionprops(cc,'Area','Eccentricity'); 
idx = find([stats.Area] > 50 & [stats.Eccentricity] < 0.8); 
img_bw2 = ismember(labelmatrix(cc),idx);
% figure; imagesc(img_bw2); colormap(gray);

imgr = imresize((~img_bw2),[28 28])*255;
% figure; imagesc(imgr); colormap(gray);
img = (reshape(imgr',1,[]))';

end