#include <opencv2/core.hpp>#include <opencv2/highgui.hpp>#include <iostream>#include <math.h>#include <complex>constintheight=128, width=128, channel=3;
intT=8;
intK=8;
structdct_str {
doublecoef[height][width][channel];
};
dct_strdct(cv::Matimg, dct_strdct_s){
doubleI;
doubleF;
doubleCu, Cv;
for (intys=0; ys<height; ys+=T){
for (intxs=0; xs<width; xs+=T){
for (intc=0; c<channel; c++){
for (intv=0; v<T; v++){
for (intu=0; u<T; u++){
F=0;
if (u==0){
Cu=1./sqrt(2);
} else{
Cu=1;
}
if (v==0){
Cv=1./sqrt(2);
}else {
Cv=1;
}
for (inty=0; y<T; y++){
for(intx=0; x<T; x++){
I= (double)img.at<cv::Vec3b>(ys+y, xs+x)[c];
F+=2./T*Cu*Cv*I*cos((2.*x+1) *u*M_PI/2./T) *cos((2.*y+1) *v*M_PI/2./T);
}
}
dct_s.coef[ys+v][xs+u][c] =F;
}
}
}
}
}
returndct_s;
}
cv::Matidct(cv::Matout, dct_strdct_s){
doublef;
doubleCu, Cv;
for(intys=0; ys<height; ys+=T){
for(intxs=0; xs<width; xs+=T){
for(intc=0; c<channel; c++){
for(inty=0; y<T; y++){
for(intx=0; x<T; x++){
f=0;
for (intv=0; v<K; v++){
for (intu=0; u<K; u++){
if (u==0){
Cu=1./sqrt(2);
} else {
Cu=1;
}
if (v==0){
Cv=1./sqrt(2);
} else {
Cv=1;
}
f+=2./T*Cu*Cv*dct_s.coef[ys+v][xs+u][c] *cos((2.*x+1) *u*M_PI/2./T) *cos((2.*y+1) *v*M_PI/2./T);
}
}
f=fmin(fmax(f, 0), 255);
out.at<cv::Vec3b>(ys+y, xs+x)[c] = (uchar)f;
}
}
}
}
}
returnout;
}
intmain(intargc, constchar*argv[]){
cv::Matimg=cv::imread("lena.jpg", cv::IMREAD_COLOR);
dct_strdct_s;
cv::Matout=cv::Mat::zeros(height, width, CV_8UC3);
dct_s=dct(img, dct_s);
out=idct(out, dct_s);
cv::imwrite("out.jpg", out);
cv::destroyAllWindows();
```Python代码如下:```pythonimportcv2importnumpyasnpimportmatplotlib.pyplotasplt# DCT hyoer-parameter 超参数T=8K=8channel=3# DCT weightdefw(x, y, u, v):
cu=1.cv=1.ifu==0:
cu/=np.sqrt(2)
ifv==0:
cv/=np.sqrt(2)
theta=np.pi/ (2*T)
return (( 2*cu*cv/T) *np.cos((2*x+1)*u*theta) *np.cos((2*y+1)*v*theta))
# DCTdefdct(img):
H, W, _=img.shapeF=np.zeros((H, W, channel), dtype=np.float32)
forcinrange(channel):
foryiinrange(0, H, T):
forxiinrange(0, W, T):
forvinrange(T):
foruinrange(T):
foryinrange(T):
forxinrange(T):
F[v+yi, u+xi, c] +=img[y+yi, x+xi, c] *w(x,y,u,v)
returnF# IDCTdefidct(F):
H, W, _=F.shapeout=np.zeros((H, W, channel), dtype=np.float32)
forcinrange(channel):
foryiinrange(0, H, T):
forxiinrange(0, W, T):
foryinrange(T):
forxinrange(T):
forvinrange(K):
foruinrange(K):
out[y+yi, x+xi, c] +=F[v+yi, u+xi, c] *w(x,y,u,v)
out=np.clip(out, 0, 255)
out=np.round(out).astype(np.uint8)
returnout# Read imageimg=cv2.imread("imori.jpg").astype(np.float32)
# DCTF=dct(img)
# IDCTout=idct(F)
# Save resultcv2.imshow("result", out)
cv2.waitKey(0)
cv2.imwrite("out.jpg", out)