自适应中值滤波 C++程序
时间: 2023-11-14 13:04:19 浏览: 155
cuda立体匹配——中值滤波
5星 · 资源好评率100%
以下是一个使用C语言编写的自适应中值滤波程序:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 256
void adaptive_median_filter(int** image, int** result, int width, int height, int window_size, int max_window_size);
void main()
{
int i, j;
int** image;
int** result;
int width, height;
int window_size, max_window_size;
// 读取图像
FILE* fp;
fp = fopen("lena.raw", "rb");
if (fp == NULL)
{
printf("Could not open file\n");
exit(0);
}
width = height = MAX_SIZE;
image = (int**)malloc(height * sizeof(int*));
result = (int**)malloc(height * sizeof(int*));
for (i = 0; i < height; i++)
{
image[i] = (int*)malloc(width * sizeof(int));
result[i] = (int*)malloc(width * sizeof(int));
fread(image[i], sizeof(int), width, fp);
}
fclose(fp);
// 执行自适应中值滤波
window_size = 3;
max_window_size = 7;
adaptive_median_filter(image, result, width, height, window_size, max_window_size);
// 保存图像
fp = fopen("lena_filtered.raw", "wb");
for (i = 0; i < height; i++)
{
fwrite(result[i], sizeof(int), width, fp);
}
fclose(fp);
// 释放内存
for (i = 0; i < height; i++)
{
free(image[i]);
free(result[i]);
}
free(image);
free(result);
}
void adaptive_median_filter(int** image, int** result, int width, int height, int window_size, int max_window_size)
{
int i, j, k, l, m, n, p;
int med, zmin, zmax, zmed, zxy;
int window[MAX_SIZE * MAX_SIZE];
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
// 获取当前窗口大小
int size = window_size;
while (size <= max_window_size)
{
// 构造窗口
int cx = j - size / 2;
int cy = i - size / 2;
int count = 0;
for (k = 0; k < size; k++)
{
for (l = 0; l < size; l++)
{
if (cx + l >= 0 && cx + l < width && cy + k >= 0 && cy + k < height)
{
window[count++] = image[cy + k][cx + l];
}
}
}
// 求中值和最小最大值
med = window[count / 2];
zmin = window[0];
zmax = window[count - 1];
zmed = 0;
for (k = 0; k < count; k++)
{
if (window[k] > zmin && window[k] < zmax)
{
zmed = window[k];
break;
}
}
// 判断当前像素是否为脉冲噪声
if (zmed > zmin && zmed < zmax)
{
zxy = image[i][j];
if (zxy > zmin && zxy < zmax)
{
result[i][j] = zxy;
}
else
{
result[i][j] = zmed;
}
break;
}
// 将窗口扩大一格
size += 2;
}
// 如果窗口大小已经达到最大值,直接取中值
if (size > max_window_size)
{
result[i][j] = med;
}
}
}
}
```
该程序读取一幅灰度图像(文件名为lena.raw),并执行自适应中值滤波,将滤波结果保存为lena_filtered.raw。程序中的窗口大小从3开始逐渐扩大,直到达到最大值为止。如果当前像素被判断为脉冲噪声,则直接使用原始像素值或中值进行替换。如果窗口大小已经达到最大值,直接使用中值进行替换。
注意,这里假设图像的像素值为整数类型,如果是浮点数类型需要做一些修改。
阅读全文