Skip to content

Instantly share code, notes, and snippets.

@n0rbed
Created March 26, 2026 13:38
Show Gist options
  • Select an option

  • Save n0rbed/7e854019b800e28e9d58a547c72aa773 to your computer and use it in GitHub Desktop.

Select an option

Save n0rbed/7e854019b800e28e9d58a547c72aa773 to your computer and use it in GitHub Desktop.
dct and idct
clear;
clear all;
%Read image "Fig2.jpg"
%Image=imread('Fig2.jpg');
Image=imread('cameraman.tif');
imshow(Image)
Block=double(Image(1:8,1:8)); %take the first block as an example
disp("original block")
disp(Block)
function table = Block8_DCT(block)
table = zeros(8, 8);
higher_energy_factor = 1;
for u = 0:7
for v = 0:7
if u == 0 && v == 0
% The single DC component needs to be divided by 4
% (Or divided by 2 twice, once for the row, once for the col)
higher_energy_factor = 1/4;
elseif u == 0 || v == 0
% The other 14 values in row 0 and col 0 are divided by 2
higher_energy_factor = 1/2;
else
% The remaining 49 values get no extra division
higher_energy_factor = 1;
end
% Accumulate the weighted sum over all spatial samples
total = 0;
for x = 0:7
for y = 0:7
basis = cos((2*x + 1) * u * pi / 16) * ...
cos((2*y + 1) * v * pi / 16);
total = total + block(x+1, y+1) * basis;
end
end
table(u+1, v+1) = (1/16) * higher_energy_factor * total;
end
end
end
dct_out=Block8_DCT(Block);
disp(dct_out)
function block = Block8_IDCT(dct_out)
block = zeros(8, 8);
for x = 0:7
for y = 0:7
total = 0;
for u = 0:7
for v = 0:7
basis = cos((2*x + 1) * u * pi / 16) * ...
cos((2*y + 1) * v * pi / 16);
total = total + dct_out(u+1, v+1) * basis;
end
end
block(x+1, y+1) = total;
end
end
end
out1=Block8_IDCT(dct_out);
disp("Recovered block using my own idct function")
disp(Block - out1)
%{
output:
1.0e-12 *
-0.1137 0.0568 0.0284 -0.2274 0 -0.1137 -0.2274 0.1137
0.0853 0 0.0284 -0.0853 0.0853 -0.0284 -0.1137 0.0284
-0.0853 0.1421 0.1421 -0.0853 0.0284 0.1421 0.0284 0.1421
-0.1421 -0.0853 0 -0.1705 -0.0568 -0.1705 -0.0853 0.0284
-0.0284 -0.0284 0.1705 -0.1137 0.1137 0 -0.0284 0.1421
-0.0284 0.0284 -0.0284 -0.0853 0.0284 0.0853 -0.0853 0.0853
0.0284 -0.0568 -0.0284 -0.1990 0.0853 -0.0853 -0.1705 -0.0284
0.0568 0.1705 0.1421 0.0568 0.1705 0.1705 0 0.1705
Which are very close to zero, meaning that our output is correct!
%}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment