均值、中值滤波代码,使用STL的vector容器。
代码及测试数据下载地址:[http://download.csdn.net/detail/hujingshuang/9341543](http://download.csdn.net/detail/hujingshuang/9341543)
~~~
/*****************************************
Copyright (c) 2015 Jingshuang Hu
@filename:demo.cpp
@datetime:2015.12.09
@author:HJS
@e-mail:jingshuang_hu@163.com
@blog:http://blog.csdn.net/hujingshuang
*****************************************/
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
//读数据
bool data_read(vector<int> *vec){
FILE *fp = fopen("data.txt", "r");
if (!fp){
cout<<"open failed!"<<endl;
return 1;
}//end if
int val = 0;
while(!feof(fp)){
fscanf(fp, "%d", &val);
vec->push_back(val);
}//end while
fclose(fp);
return 0;
}
//写数据
bool data_write(vector<int>vec1, vector<int>vec2){
if (vec1.empty() && vec2.empty()){
cout<<"mean_filter or median_filter failed!"<<endl;
return 1;
}//end if
FILE *fp;
fp = fopen("mean_filter.txt", "w");
vector<int>::iterator it;
for (it = vec1.begin(); it != vec1.end(); ++it){
fprintf(fp, "%d\n", *it);
}//end for
fclose(fp);
fp = fopen("median_filter.txt", "w");
for (it = vec2.begin(); it != vec2.end(); ++it){
fprintf(fp, "%d\n", *it);
}//end for
fclose(fp);
return 0;
}
//均值滤波
vector<int> mean_filter(vector<int>vec, int scale){
int sum = 0;
vector<int>temp;
for (int i = 0; i < vec.size() - scale; ++i){
for (int j = 0; j < scale; ++j){
sum += vec.at(i + j);
}//end for
temp.push_back((int)(sum / scale));
sum = 0;
}//end for
return temp;
}
//中值滤波
vector<int> median_filter(vector<int>vec, int scale){
vector<int>dst, temp;
dst.resize(scale);
for (int i = 0; i < vec.size() - scale; ++i){
partial_sort_copy(vec.begin() + i, vec.begin() + i + scale, dst.begin(), dst.end());
temp.push_back(dst.at((int)(scale / 2)));
}//end for
return temp;
}
//主函数
int main(){
vector<int>vec, vec1, vec2;
int scale = 9;
data_read(&vec);
vec1 = mean_filter(vec, scale);
vec2 = median_filter(vec, scale);
data_write(vec1, vec2);
return 0;
}//end main
~~~