% ::::::::::::::::::::::::::::::::::::::::::::::::::::::: %
% Solution proposal to programming exercises week 7       %
%                                                         %
% INF2310, spring 2017                                    %
%                                                         %
% Ole-Johan Skrede, 18.02.2017                            %
% ::::::::::::::::::::::::::::::::::::::::::::::::::::::: %

% :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: %
% Test implementation of convolution. Apply it on gradient images.   %
% :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: %
graphics_toolkit("gnuplot")
crash_dumps_octave_core(0)

in_image_filename = 'car.png'
in_path = [pwd '/../../../assets/images/'];
result_path = [pwd '/../results/matlab'];

im = imread([in_path in_image_filename]);
disp(class(im))
disp(min(min(im)))
disp(max(max(im)))
plot_image(im, 'Original')

% Convoluted image will be of the same size as the in-image.
% Positive y-direction is to the right, positive x-direction is downwards.

% Vertical gradient
filter_x_h = [1 2 1];
filter_x_v = [1 0 -1]';
filter_x = filter_x_v * filter_x_h

gx_1d = convolution1dH(im, filter_x_h);
gx_1d = convolution1dV(gx_1d, filter_x_v);
gx_2d = convolution2d(im, filter_x);

printf('Vertical gradient max abs diff: %f \n', max(abs(gx_1d - gx_2d)(:)))

plot_image(gx_1d, 'Vertical gradient')
imwrite(scale_uint8(gx_1d, 0., 255.), [result_path '/grad_x_' in_image_filename])

% Horisontal gradient
filter_y_h = [1 0 -1];
filter_y_v = [1 2 1]';
filter_y = filter_y_v * filter_y_h

gy_1d = convolution1dH(im, filter_y_h);
gy_1d = convolution1dV(gy_1d, filter_y_v);
gy_2d = convolution2d(im, filter_y);

printf('Vertical gradient max abs diff: %f \n', max(abs(gy_1d - gy_2d)(:)))

plot_image(gy_1d, 'Horisontal gradient')
imwrite(scale_uint8(gy_1d, 0., 255.), [result_path '/grad_y_' in_image_filename])

% Gradient magnitude
grad_magn = hypot(gx_1d, gy_1d); %sqrt(gx_1d.^2 + gy_1d.^2);

plot_image(grad_magn, 'Gradient magnitude')
imwrite(scale_uint8(grad_magn, 0., 255.), [result_path '/grad_magn_' in_image_filename])

% Gradient angle
grad_angle = atan2(gy_1d, gx_1d);

plot_image(grad_angle, 'Gradient angle')
imwrite(scale_uint8(grad_angle, 0., 255.), [result_path '/grad_angle_' in_image_filename])

pause() % To keep plot window
