用c++写一个中值滤波算法
时间: 2024-01-05 19:03:21 浏览: 26
中值滤波算法是一种常见的图像处理算法,可以有效地减少图像中的噪声。下面是一个用 C++ 实现的简单中值滤波算法:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 中值滤波算法
void median_filter(vector<int>& image, int width, int height, int kernel_size) {
int kernel_radius = kernel_size / 2;
// 遍历图像像素
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
// 获取当前像素的领域像素
vector<int> kernel;
for (int j = -kernel_radius; j <= kernel_radius; ++j) {
for (int i = -kernel_radius; i <= kernel_radius; ++i) {
int px = x + i;
int py = y + j;
if (px >= 0 && px < width && py >= 0 && py < height) {
kernel.push_back(image[py * width + px]);
}
}
}
// 对领域像素进行排序,计算中值
sort(kernel.begin(), kernel.end());
int median = kernel[kernel_size / 2];
// 将中值赋值给当前像素
image[y * width + x] = median;
}
}
}
int main() {
int width = 10;
int height = 10;
int kernel_size = 3;
// 随机生成图像
vector<int> image(width * height);
for (int i = 0; i < width * height; ++i) {
image[i] = rand() % 256;
}
// 输出原始图像
cout << "Original Image:" << endl;
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
cout << image[y * width + x] << " ";
}
cout << endl;
}
// 中值滤波
median_filter(image, width, height, kernel_size);
// 输出处理后的图像
cout << "Filtered Image:" << endl;
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
cout << image[y * width + x] << " ";
}
cout << endl;
}
return 0;
}
```
这个实现中,我们使用了一个二维向量 `image` 存储图像像素值,使用 `median_filter` 函数进行中值滤波。在函数中,我们遍历每个像素,获取其周围 `kernel_size` × `kernel_size` 个像素值,然后对这些像素值进行排序,取其中位数作为该像素的新值。最后输出处理后的图像。