%% 2D convolution example
clear all; close all; clc
format compact; format shortg

load mandrill

figure(1)
imagesc(X), colormap(gray)
title('original image')

%% two ways to generate filters in Matlab:
% option 1 (using MATLAB's fspecial)
filt_size = 5;
H_avg = fspecial('average',filt_size);
H_avg
commandwindow
X_avg_blur  = conv2(X,H_avg);
figure(2); imagesc(X_avg_blur), colormap(gray)
title('average blur')

%% gaussian blur

H_gauss = fspecial('gaussian',3,1);
H_gauss

%% option 2: get your hands dirty

x_len = 5; %should be odd!!
y_len = 5; %ibid. As these grow we average over a wider interval
sigma_x = 1e-1; %as these grow, we get closer to 
sigma_y = 1e0; %approximating the averaging kernel

[xx, yy] = meshgrid(linspace(-1,1,x_len), linspace(-1,1,y_len));
Z = exp(-1*yy.^2/(2*sigma_y^2)).*exp(-1*xx.^2/(2*sigma_x^2))/(2*pi);
%note that this way you can even convolve with weirder gaussian kernels
Z  = Z/sum(sum(Z));% they normalize by sum(sum(Z))
Z

if size(Z) == size(H_gauss)
   fprintf('Z./H_gauss is\n')
   Z./H_gauss
end


figure(3)
X_gauss_blur = conv2(Z,X);
imagesc(X_gauss_blur); colormap(gray)
title('Gaussian blur')


%% Other filter examples

H_sobel = fspecial('sobel'); % filter for approximating the vertical gradient


X_sobel_h = conv2(H_sobel,X);
X_sobel_v = conv2(H_sobel',X);

figure(4);
subplot(2,1,1)
% note we plot the absolute value here, direction of gradient is
% not that helpful compared to the magnitude
imagesc(abs(X_sobel_h)); colormap(gray);
title('Sobel filtered, horizontal edges')
subplot(2,1,2)
imagesc(abs(X_sobel_v)); colormap(gray);
title('Sobel filtered, vertical edges')



