均值滤波的分离滤波器 c++
时间: 2023-10-25 13:17:19 浏览: 92
以下是分离均值滤波器的C语言实现代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define WIDTH 640
#define HEIGHT 480
void separable_mean_filter(unsigned char* input, unsigned char* output, int width, int height, int kernel_size)
{
int i, j, k;
int radius = (kernel_size - 1) / 2;
int kernel_sum = kernel_size * kernel_size;
// Allocate memory for temporary arrays
unsigned char* temp_h = (unsigned char*)malloc(width * height * sizeof(unsigned char));
unsigned char* temp_v = (unsigned char*)malloc(width * height * sizeof(unsigned char));
// Apply horizontal filter
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
int sum = 0;
for (k = -radius; k <= radius; k++)
{
int idx = j + k;
if (idx < 0)
idx = -idx;
else if (idx >= width)
idx = width - (idx - width) - 1;
sum += input[i * width + idx];
}
temp_h[i * width + j] = sum / kernel_size;
}
}
// Apply vertical filter
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
int sum = 0;
for (k = -radius; k <= radius; k++)
{
int idx = i + k;
if (idx < 0)
idx = -idx;
else if (idx >= height)
idx = height - (idx - height) - 1;
sum += temp_h[idx * width + j];
}
temp_v[i * width + j] = sum / kernel_size;
}
}
// Copy result to output array
for (i = 0; i < width * height; i++)
{
output[i] = temp_v[i];
}
// Free memory
free(temp_h);
free(temp_v);
}
int main()
{
unsigned char input[WIDTH * HEIGHT];
unsigned char output[WIDTH * HEIGHT];
// Generate input image with noise
for (int i = 0; i < WIDTH * HEIGHT; i++)
{
input[i] = rand() % 256;
}
separable_mean_filter(input, output, WIDTH, HEIGHT, 5);
// Save output image
FILE* fp = fopen("output.raw", "wb");
fwrite(output, sizeof(unsigned char), WIDTH * HEIGHT, fp);
fclose(fp);
return 0;
}
```
阅读全文