我正在尝试使用1D DCT操作将2D离散余弦变换应用于图像。如果我将其与dct2
MATLAB函数进行比较,我的输出结果是不正确的。我不明白我的代码出了什么问题以及在哪里出了问题。
如果有人能指出错误或提供任何其他建议,那将非常有帮助。
这是我用MATLAB编写的代码:
% main function
signal=rand(100);
signal_dct=myDCT(signal);
figure; imshow((signal_dct));
% function to calculate 2D DCT of an image
function res=myDCT(signal)
signal=double(signal);
l=size(signal,1);
res=zeros(l); %initialize the final result matrix
for k=1:l %calculate 1D DCT of each row of image
res(k,:)=mdct(signal(k,:));
end
for k=1:l %calculate 1D DCT of each column of image
res(:,k)=mdct(res(:,k));
end
end
%% function to calculate 1D DFT of a 1D signal
function res=mdct(signal)
l=size(signal,1);
for i=1:l
if i==1 %for signal index of 1, alpha is 1/sqrt(l)
alpha=sqrt(1/l);
else %for signal index of greater than 1
alpha=sqrt(2/l);
end
j=[1:l];
% summation calculates single entry of res by applying the
% formula of DCT on the signal
summation=sum(sum(signal(j)*cos((pi*(2*(j-1)+1)*(i-1))/(2*l))));
res(i)=alpha*summation;
end
end
cosd
函数。请改用cos
函数。 - Luis Mendo