我在Matlab中开发了一个计算图像DCT (离散余弦变换)的函数。我不知道在我的代码中不起作用的是什么,它是用于图像compression.please帮助我的。请给我任何想法。
clc;close all;clear all;
image=('cameraman.tif');
[h w] = size(image);
image = double(image) - 128;
b=8;
block = zeros(b,b);
image_t=zeros(size(image));
for k=1:b:h
for l=1:b:w
image_t(k:k+b-1,l:l+b-1)= image(k:k+b-1,l:l+b-1);
for u=1:b
for v=1:b
if u == 0
Cu = 1/sqrt(2);
else
Cu = 1;
end
if v == 0
Cv = 1/sqrt(2);
else
Cv = 1;
end
Res_sum=0;
for x=1:b;
for y=1:b
Res_sum = Res_sum + ((image_t(x,y))*cos(((2*x)+1)*u*pi/(2*b))*cos(((2*y)+1)*v*pi/(2*b)));
end
end
dct= (1/4)*Cu*Cv*Res_sum;
block(u,v) = dct;
end
end
image_comp(k:k+b-1,l:l+b-1)=block(u,v);
end
end
end发布于 2015-04-09 11:33:30
我假设您为DCT实现了以下公式:

使用

我想你需要把图像分割成8x8块,然后对每个块做离散余弦变换。
if u == 0或if v == 0中的部分,因为您在通过1:b的for循环中遍历u和v。根本的问题是MATLAB从1开始索引,而DCT中的频率从0开始。我的提示是:使用u和v作为频率,就像公式中的频率一样,而不是像索引那样,即for u=0:b-1和u+1。x和y也是如此。image_t应该只包含当前块(因此我将它重命名为current_block),而不是整个映像。那是current_block = image(k:k+b-1,l:l+b-1);dct= (1/4)*Cu*Cv*Res_sum;中,不应该是1/4,而应该是1/sqrt(2*N),其中N是块大小(您称之为b),因此是1/sqrt(2*b)。对于8的块大小,如您的示例所示,这当然是1/4。image是MATLAB函数的名称。最好不要将它用作函数名。考虑将其更改为input_image。128,请考虑一下为什么要这样做。这将导致下面的代码。我不知道这是否解决了你所有的问题,但你现在应该离这更近些;-)
PS:考虑将代码向量化以提高性能。
function image_comp = dctII(input_image, b)
[h, w] = size(input_image);
input_image = double(input_image);
block_dct = zeros(b);
% Loop through all blocks
for k=1:b:h
for l=1:b:w
% Save true image of block
current_block = input_image(k:k+b-1,l:l+b-1);
% Loop through all cos frequencies (u,v)
for u=0:b-1
for v=0:b-1
if u == 0
Cu = 1/sqrt(2);
else
Cu = 1;
end
if v == 0
Cv = 1/sqrt(2);
else
Cv = 1;
end
Res_sum = 0;
% Loop through all pixel values
for x=0:b-1
for y=0:b-1
Res_sum = Res_sum + ((current_block(x+1,y+1))*cos(((2*x)+1)*u*pi/(2*b))*cos(((2*y)+1)*v*pi/(2*b)));
end
end
% Calculate DCT value at frequency (u,v)
dct = 1/sqrt(2*b) * Cu * Cv * Res_sum;
block_dct(u+1,v+1) = dct;
end
end
image_comp(k:k+b-1,l:l+b-1) = block_dct(u+1,v+1);
end
end
end % of functionhttps://stackoverflow.com/questions/29534039
复制相似问题