Thursday, June 30, 2016

Haar wavelet with Matlab implementation

Haar wavelet is among the most simplest wavelets, and it has some application in various field such as signal processing and image processing.

The following is just a implementation of Haar wavelet in Matlab script. The key is not the implementation, but some insight into wavelet:
(1) Taking image processing for example, the most exact image is the original image, so for processing, like compression, the key question is to which extent one can tolerate the entropy to increase, that means suppose the image I belongs to space V(J), you can only play with the image scattering entropy among V(j) with j < J.
(2) When comparing data in Matlab, always pay attention to the scale, I didn't pay much attention to the notation like "1.0e-15 *", so originally I thought there's wrong implementation in my code, later I realize all is correct.

The script is as follows:

function wavelet_2d_forward_and_inverse(img_path)

img = imread(img_path, 'jpg');
img = im2double(rgb2gray(img));

figure;
imshow(img);
title('Original image');

[m, n] = size(img);

if m ~= n
    disp('only squared image supported');
    return;
end

coeff = 1 / 2 ^ 0.5;

% generate row approximation and detail matrix
HR = zeros(n / 2, n);
GR = zeros(n / 2, n);

for i = 1 : n / 2;
    HR(i, 2 * i - 1) = coeff;
    GR(i, 2 * i - 1) = coeff;
    HR(i, 2 * i) = coeff;
    GR(i, 2 * i) = -1 * coeff;
end

% generate column approximation and detail matrix
HC = zeros(m / 2, m);
GC = zeros(m / 2, m);

for i = 1 : m / 2;
    HC(i, 2 * i - 1) = coeff;
    GC(i, 2 * i - 1) = coeff;
    HC(i, 2 * i) = coeff;
    GC(i, 2 * i) = -1 * coeff;
end

% calculate the approximation and detail parts respectively
img_c = HC * img * HR';
img_d1 = GC * img * HR';
img_d2 = HC * img * GR';
img_d3 = GC * img * GR';

img_W = [img_c img_d1; img_d2 img_d3];

img2 = mat2gray(img_W);
figure;
imshow(img2);
title('Forward Haar transform');

% inverse transformation
HR_adj = HR';
GR_adj = GR';
HC_adj = HC';
GC_adj = GC';

img_orig = HC_adj * img_c * HR_adj'  + ...
    GC_adj * img_d1 * HR_adj' + ...
    HC_adj * img_d2 * GR_adj' + ...
    GC_adj * img_d3 * GR_adj';

img3 = mat2gray(img_orig);
figure;
imshow(img3);
title('Inverse Haar transform');  

The images are as follows: