题目信息
对给定灰度图像src,按照给定的滤波器大小进行均值滤波,输出图像滤波结果dst。
要求:
1.对图像边界处的运算,在范围外的图像,内容按零处理。
2.运算结束需要四舍五入,按整型数输出结果,不用对数据范围进行处理,即输出可以大于255.
滤波器大小为奇数。
vector<vector<int>> blur(vector<vector<int>>src,
int height_filter,
int width_filter)
src:待处理的图像 int[]
dst:处理结果
height_src:输入图像的高。即src.size()
width_src:输入图像的宽。即src[0].size()。
height_filter:滤波器的高。
width_filter:滤波器的宽。
1 <= src.size() <= 10000
1 <= src[0].size() <= 10000
1 <= height_filter <= 10000
1 <= width_filter <= 10000
输入
height_src,
width_src,
heiht_filter,
width_filter,
height_src行 width_src列的图像矩阵数据。
输出
height_src行 width_src列的均值滤波结果。(空格相隔)
测试样例
5 5
3 3
9 0 6 2 2
9 7 6 2 10
3 5 9 9 7
7 5 8 0 5
2 9 6 5 5
3 4 3 3 2
4 6 5 6 4
4 7 6 6 4
3 6 6 6 3
3 4 4 3 2
解答
#include <iostream>
#include <vector>
using namespace std;
int int_part(double x)
{
return (int) (x + 0.5);
}
vector<vector<int>> blur(vector<vector<int>> src,
int height_filter,
int width_filter)
{
int height_side = (height_filter - 1) / 2;
int width_side = (width_filter - 1) / 2;
int height_src = src.size();
int width_src = src[0].size();
double sum = height_filter * width_filter;
vector<vector<int>> dst;
for (int i = 0; i < height_src; i++)
{
vector<int> line;
for (int j = 0; j < width_src; j++)
{
int num = 0;
for (int p = i - height_side; p <= i + height_side; p++)
{
for (int q = j - width_side; q <= j + width_side; q++)
{
if (p < 0 || q < 0 || p >= height_src || q >= width_src)
{
num += 0;
}
else
{
num += src[p][q];
}
}
}
line.push_back(int_part(num / sum));
}
dst.push_back(line);
}
return dst;
}
int main()
{
freopen("/Users/zhj/Downloads/test.txt", "r", stdin);
int height_src;
int width_src;
int height_filter;
int width_filter;
cin >> height_src >> width_src >> height_filter >> width_filter;
vector<vector<int>> src;
for (int i = 0; i < height_src; i++)
{
vector<int> line;
for (int j = 0; j < width_src; j++)
{
int tmp;
cin >> tmp;
line.push_back(tmp);
}
src.push_back(line);
}
vector<vector<int>> dst = blur(src, height_filter, width_filter);
for (unsigned int i = 0; i < src.size(); i++)
{
for (unsigned int j = 0; j < src[0].size(); j++)
{
cout << dst[i][j] << " ";
}
cout << endl;
}
return 0;
}