Ashar
Ashar

Reputation: 774

Problem reconstructing the image using inverse DCT in Matlab

I implemented my own 2D DCT using 1D DCT and IDCT. My DCT results are matching with the Matlab's implementation but IDCT is giving a different result. The difference is not totally off as can be seen by the reconstructed image.

Upvotes: 0

Views: 329

Answers (1)

aosborne
aosborne

Reputation: 381

I took a crack at this - your DCT/IDCT equations didn't look quite right to me. I used the DCT-2 and DCT-3 formulas from the SciPy documentation here.

original_img  = imread('nggyu.jpeg');
transformed_img = permute(dct1d(permute( ...
                      dct1d(double(original_img)), ...
                          [2,1,3])), [2,1,3]);
recovered_img = uint8(permute(idct1d(permute( ...
                    idct1d(transformed_img), ...
                        [2,1,3])), [2,1,3]));

figure('position', [0, 0, 600, 200])
subplot(1,3,1), imshow(original_img), title 'Original'
subplot(1,3,2), imshow(log(abs(transformed_img)),[]), title 'DCT'
subplot(1,3,3), imshow(recovered_img), title 'IDCT'

function y = dct1d(x)
  % Compute normalized DCT-2 over the first dimension of the input.

  N = size(x, 1);
  y = zeros(size(x));
  n = (1:N)';
  
  for k = 1:N
    if k == 1
      scale = sqrt(1/(4*N));
    else
      scale = sqrt(1/(2*N));
    end
    
    y(k,:,:) = scale * 2 * sum(x(n,:,:) .* cos((pi/(2*N)) * (2*n-1) * (k-1)), 1);
  end
  
end

function x = idct1d(y)
  % Compute normalized DCT-3 over the first dimension of the input.

  N = size(y, 1);
  x = zeros(size(y));
  k = (2:N)';
  
  for n = 1:N
    x(n,:,:) = y(1,:,:)/sqrt(N) + sqrt(2/N) * sum(y(k,:,:) .* cos((pi/(2*N)) * (2*n-1) * (k-1)), 1);
  end
  
end

enter image description here

Upvotes: 1

Related Questions