1. 理想低通滤波

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<iostream>
#include<opencv2/opencv.hpp>
#include"mydft.h"
#include"Salt.h"

using namespace std;
using namespace cv;

int main(){
Mat img,img_gray,img_out,img_transform;
img = imread("/home/v/home.png");
if (img.empty()){
cout<<"can't open image"<<endl;
return -1;
}

imshow("img",img);
cvtColor(img,img_gray,COLOR_BGR2GRAY);

Salt(img_gray,10000);
imshow("img_gray",img_gray);

//1. 傅里变换,img_out为可显示的频谱图,img_transform为傅里叶变换的复数结果
mydft(img_gray,img_out,img_transform);
imshow("img_out",img_out);

//2. 理想低通滤波
Mat plances[] = {Mat_<float>(img_out),Mat::zeros(img_out.size(),CV_32F)};
split(img_transform,plances); // 分离通道,获取实部和虚部
Mat img_tansform_real = plances[0];
Mat img_tansform_imag = plances[1];

int core_x = img_tansform_real.rows/2;
int core_y = img_tansform_real.cols/2;
int r = 80; // 滤波半径

for(int i=0;i<img_tansform_real.rows;i++){
for(int j=0;j<img_tansform_real.cols;j++){
//距离中心的距离大于设置半径r的点所在值设为0
if((i-core_x)*(i-core_x)+(j-core_y)*(j-core_y)>r*r){
img_tansform_real.at<float>(i,j) = 0;
img_tansform_imag.at<float>(i,j) = 0;
}
}
}

plances[0] = img_tansform_real;
plances[1] = img_tansform_imag;
Mat img_transform_ilpf; // 定义理想低通滤波矩阵
merge(plances,2,img_transform_ilpf);

//3. 傅里叶变换
Mat iDft[] = {Mat_<float>(img_out),Mat::zeros(img_out.size(),CV_32F)};

idft(img_transform_ilpf,img_transform_ilpf); //傅里叶变换
split(img_transform_ilpf,iDft); // 傅里叶变换
magnitude(iDft[0],iDft[1],img_out); // 计算复数的幅值
normalize(iDft[0],iDft[0],0,1,NORM_MINMAX); // 归一化处理
imshow("idft",iDft[0]); // 显示逆变换图像

waitKey(0);
return 0;
}