Advertisement
Guest User

Untitled

a guest
Jan 16th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. %% Compress colored image with PCA algorithm
  2. clear
  3. close all
  4. clc
  5.  
  6. A = double(imread('blue_bird.jpg'));
  7.  
  8. % Display original image
  9. subplot(1, 2, 1);
  10. imagesc(A/255)
  11. title('Original image')
  12.  
  13. % Convert image to 2d
  14. img_size = size(A);
  15. X = reshape(A, img_size(1) * img_size(2), 3);
  16.  
  17. % Normalize data before performing PCA
  18. [X_norm, mu, sigma] = featureNormalize(X);
  19.  
  20. % Run PCA
  21. [U, S] = pca(X_norm);
  22.  
  23. % Reduce data to the first 2 eigenvectors
  24. K = 2;
  25. Z = projectData(X_norm, U, K);
  26.  
  27. % Convert back to 3d and display compressed image
  28. Q = reshape((X_norm+mu).*sigma, img_size(1),img_size(2), 3);
  29. subplot(1, 2, 2);
  30. imagesc(Q/255);
  31. title('Compressed image')
  32.  
  33. % Create the new compressed image
  34. imwrite(Q,'blue_bird_compressed.jpg');
  35.  
  36. % Find out how much space we saved
  37. original = dir('blue_bird.jpg');
  38. compressed = dir('blue_bird_compressed.jpg');
  39. oSize = original.bytes;
  40. cSize = compressed.bytes;
  41. saved = (1-(cSize/oSize))*100;
  42.  
  43. disp(['Before: ', num2str(oSize), ' bytes']);
  44. disp(['After: ', num2str(cSize), ' bytes']);
  45. disp([num2str(saved), '% space saved']);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement