c语言实现图像中值滤波去噪
时间: 2023-08-01 10:14:19 浏览: 118
c语言实现中值滤波的程序代码
5星 · 资源好评率100%
以下是使用C语言实现图像中值滤波的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define WIDTH 512
#define HEIGHT 512
int main()
{
// 读取图像
FILE* fp;
fp = fopen("lena_noise.raw", "rb");
unsigned char* img = (unsigned char*)malloc(sizeof(unsigned char) * WIDTH * HEIGHT);
fread(img, sizeof(unsigned char), WIDTH * HEIGHT, fp);
fclose(fp);
// 中值滤波
unsigned char* res = (unsigned char*)malloc(sizeof(unsigned char) * WIDTH * HEIGHT);
int window_size = 3; // 窗口大小
int half_win = window_size / 2;
int* values = (int*)malloc(sizeof(int) * window_size * window_size);
int index = 0;
for (int i = half_win; i < HEIGHT - half_win; i++) {
for (int j = half_win; j < WIDTH - half_win; j++) {
index = 0;
for (int k = -half_win; k <= half_win; k++) {
for (int l = -half_win; l <= half_win; l++) {
*(values + index) = *(img + (i + k) * WIDTH + (j + l));
index++;
}
}
// 对窗口内像素值进行排序
for (int k = 0; k < window_size * window_size - 1; k++) {
for (int l = k + 1; l < window_size * window_size; l++) {
if (*(values + l) < *(values + k)) {
int tmp = *(values + k);
*(values + k) = *(values + l);
*(values + l) = tmp;
}
}
}
// 取中值并保存
*(res + i * WIDTH + j) = (unsigned char)*(values + window_size * window_size / 2);
}
}
// 输出图像
fp = fopen("lena_median.raw", "wb");
fwrite(res, sizeof(unsigned char), WIDTH * HEIGHT, fp);
fclose(fp);
return 0;
}
```
这个示例代码读取一张名为lena_noise.raw的灰度图像,使用中值滤波进行去噪,最终将结果图像保存为lena_median.raw。在中值滤波中,我们使用一个窗口对每个像素进行处理,将窗口内的像素值进行排序,取中值作为该像素的新值。窗口大小可以根据实际需要进行调整。
阅读全文