Skip to content

Instantly share code, notes, and snippets.

@Ginurx
Last active November 21, 2023 04:23
Show Gist options
  • Save Ginurx/d030987fe086d415f7d8e5a2e7f40b7f to your computer and use it in GitHub Desktop.
Save Ginurx/d030987fe086d415f7d8e5a2e7f40b7f to your computer and use it in GitHub Desktop.
a Matlab code snippet to compress a RGB image to a two-component image, two basis vectors and an offset.
orignalImage = im2double(imread('grass.tif'));
m = size(orignalImage, 1);
n = size(orignalImage, 2);
piexelNum = m * n;
X = reshape(orignalImage, [piexelNum, 3]);
avg = mean(X);
X2 = X - avg;
[U, S, V] = svd(X2, 'econ');
U2 = U(:, [1 2]);
S2 = S([1 2], [1 2]);
V2 = V(:, [1 2]);
% Reconstruct the image
% avg : offset color vector for the entire image
% S2 * V2' : an 2x3 matrix where each row corresponds to a basis vector
% U2 : two coefficients per pixel with respect to the two basis
reconstructedImage = U2 * (S2 * V2') + avg;
figure;
axis off;
subplot(1, 3, 1);
image(reshape(orignalImage, [m, n, 3]));
title('original');
subplot(1, 3, 2);
image(reshape(reconstructedImage, [m, n, 3]));
title('reconstructed');
subplot(1, 3, 3);
% scaled by a factor of 100 to see the differences
diff = rgb2gray(imabsdiff(X, reconstructedImage)) * 100;
imagesc(reshape(diff, [m, n, 3]));
title('diff (×100)');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment