% toltsuk be a Matlab beepitett digits adathalmaz tanuloadatait (a szamjegyekhez most
% csak a dolesi szogekre vagyunk kivancsiak
[trainImages,~,trainAngles]=digitTrain4DArrayData;

%nezzuk meg az elso 20 kepet
figure
for i=1:20
   subplot(4,5,i)
   imshow(trainImages(:,:,:,i))
end

%irassuk ki az elso 20 kephez tartozo szogeket
trainAngles(1:20)

layers = [ imageInputLayer([28 28 1])
           convolution2dLayer(12,25)
           reluLayer
           fullyConnectedLayer(1)
           regressionLayer];
       
 options = trainingOptions('sgdm','InitialLearnRate',0.001, ...
    'MaxEpochs',15);

net = trainNetwork(trainImages,trainAngles,layers,options);

%toltsuk be a tesztadatokat
[testImages,~,testAngles] = digitTest4DArrayData;
predictedTestAngles = predict(net,testImages);
numTestImages = size(testImages,4);
%49 veletlenszeruen valasztott kepet forgassunk vissza a becsult
%dolesszoggel
idx = randperm(numTestImages,49);
for i = 1:numel(idx)
    image = testImages(:,:,:,idx(i));
    predictedAngle = predictedTestAngles(idx(i));

    imagesRotated(:,:,:,i) = imrotate(image,predictedAngle,...
        'bicubic','crop');
end

figure
subplot(1,2,1)
montage(testImages(:,:,:,idx))
title('Original')

subplot(1,2,2)
montage(imagesRotated)
title('Corrected')

% a kepek hany szazalekanal volt az elteres 10 foknal kisebb
t=10;
accuracy=sum(abs(predictedTestAngles-testAngles)<t)/numel(testAngles)