clc; clear; close all;

I_raw = imread('cameraman.tif'); 

if ndims(I_raw) == 3
    I_gray = rgb2gray(I_raw);
else
    I_gray = I_raw;
end

I = double(I_gray);

[U, S, V] = svd(I);
sigmas = diag(S);

figure;
semilogy(sigmas, 'b-o', 'LineWidth', 1.5);
title('Singular Values Plot (Semilogy)');
xlabel('Index');
ylabel('Singular Value');
grid on;

squared_sigmas = sigmas.^2;
total_energy = sum(squared_sigmas);
cumulative_energy = cumsum(squared_sigmas);
energy_ratio = cumulative_energy / total_energy;

k = find(energy_ratio >= 0.95, 1);

fprintf('Full rank (r) = %d\n', length(sigmas));
fprintf('Required rank for 95%% energy (k) = %d\n\n', k);

I_approx = U(:, 1:k) * S(1:k, 1:k) * V(:, 1:k)';

figure;
subplot(1,2,1);
imshow(uint8(I));
title('Original Image');

subplot(1,2,2);
imshow(uint8(I_approx));
title(sprintf('Reconstructed Image with k = %d', k));

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: