Thursday, September 23, 2010

Image Compression

Using pca, this activity enabled to compress image memory in small memory packets just by storing the Eigenvectors and eigenvalues.



**CODE**
stacksize(100000000);
for vectors = [1,3,10,20,46];

img = gray_imread('Dock.jpg');
//img = (img(:,:,1) + img(:,:,2) + img(:,:,3))/3;
//imshow(img);

//cut to 10 by 10

k = 0;
for r = 1:20;
for c = 1:40;
itemp = img(((10*r-9):(10*r)) , ((10*c-9):(10*c))); //divides to 10 by 10
xtemp = itemp(:); //columnizes
k = c + (r-1)*40; //makes proper index
x(k,:) = xtemp'; //reconstructs
end
end
//imwrite(itemp, 'itemp.jpg');
//imshow(itemp);

//applying pc
[lambda, facpr, comprinc] = pca(x);



//reconstructing the image
B = [];
for i = 1:800,
A = [];
for j = 1:vectors,
recim = comprinc(i,j) * facpr(:,j);
A = [A recim]
end
A = sum(A, 'c');
B = [B A];
end

C = B';
//test reconstruction
y = zeros(200,400);
k = 0;
for r = 1:20,
for c = 1:40,
k = c +(r-1)*40;
//xtemp = facpr(:,k);
xtemp = C(k,:);
y(((10*r-9):(10*r)), ((10*c-9):(10*c))) = matrix(xtemp,10,10);
end
end
//scf(vectors);
imwrite((y-min(y))/(max(y)-min(y)), 'vectors'+string(vectors)+'.jpg');
//imshow(y);
end

**END of CODE**

What this code does is that it cuts the image into 10x10blocks. Then pca is applied onto it. Thanks to Maam Jing for the sample code that simplifies things. After PCA, the image is reconstructed. In reconstructing the image, each 10x10 block is reconstructed with the comprinc and the facpr from the pca function. Comprinc and facpr is used in image representation as superposition of weighted basis images.


Using this 200x400 pixel image:


200x400 = 80000 pixels
Reconstructed with 3, 20 and 46 eigenvectors:


800 pixels X 3 eigenimages


800pixels * 20 eigenimages


800* 46 eigenimages

In the reconstructed images, only the basis coefficients are saved. In this case, the comprinc. So, there are 800pixels plus the number of eigenvector to be saved. It drastically compressed the image compared to the 400*200pixels to be saved.

I'd rate myself 10/10 for this activity.
Thanks to Maam Jing for the handouts and the basis codes. It may the activity a lot easier. Thanks to my roomates for helping me figure out the reconstruction part of the compressed images and some debugging too. And for teaching me to append in scilab.