C语言对图像进行均值滤波
时间: 2023-10-04 12:12:42 浏览: 70
以下是C语言实现图像均值滤波的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#define ROWS 256
#define COLS 256
void mean_filter(unsigned char input[ROWS][COLS], unsigned char output[ROWS][COLS], int kernel_size)
{
int i, j, m, n, sum;
int kernel_radius = kernel_size / 2;
for (i = kernel_radius; i < ROWS - kernel_radius; i++) {
for (j = kernel_radius; j < COLS - kernel_radius; j++) {
sum = 0;
for (m = -kernel_radius; m <= kernel_radius; m++) {
for (n = -kernel_radius; n <= kernel_radius; n++) {
sum += input[i+m][j+n];
}
}
output[i][j] = sum / (kernel_size * kernel_size);
}
}
}
int main()
{
unsigned char input[ROWS][COLS];
unsigned char output[ROWS][COLS];
FILE *fp_in, *fp_out;
int i, j;
// 读取图像文件
fp_in = fopen("input_image.raw", "rb");
if (fp_in == NULL) {
printf("Cannot open input_image.raw.\n");
exit(1);
}
fread(input, sizeof(unsigned char), ROWS*COLS, fp_in);
fclose(fp_in);
// 进行均值滤波
mean_filter(input, output, 3); // kernel_size = 3
// 保存输出图像
fp_out = fopen("output_image.raw", "wb");
if (fp_out == NULL) {
printf("Cannot open output_image.raw.\n");
exit(1);
}
fwrite(output, sizeof(unsigned char), ROWS*COLS, fp_out);
fclose(fp_out);
return 0;
}
```
该代码使用了一个3x3的滤波器进行均值滤波。可以通过修改`kernel_size`变量来改变滤波器大小。`mean_filter`函数用于实现均值滤波,输入图像存储在`input`数组中,输出图像存储在`output`数组中。`main`函数用于读取输入图像文件,进行均值滤波,并保存输出图像文件。
阅读全文