讲解一下C语言写高斯模糊代码
时间: 2023-05-11 07:04:11 浏览: 219
当我们需要对图像进行模糊处理时,高斯模糊是一种常用的方法。下面是一份C语言实现高斯模糊的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#define PI 3.14159265358979323846
int main(int argc, char *argv[])
{
if (argc < 4) {
printf("Usage: %s input_image output_image radius\n", argv[0]);
return 1;
}
char *input_filename = argv[1];
char *output_filename = argv[2];
int radius = atoi(argv[3]);
int width, height, channels;
unsigned char *image = stbi_load(input_filename, &width, &height, &channels, 0);
if (image == NULL) {
printf("Error loading image %s\n", input_filename);
return 1;
}
unsigned char *output_image = malloc(width * height * channels);
if (output_image == NULL) {
printf("Error allocating memory for output image\n");
return 1;
}
double *kernel = malloc((2 * radius + 1) * sizeof(double));
if (kernel == NULL) {
printf("Error allocating memory for kernel\n");
return 1;
}
double sigma = radius / 3.0;
double sum = 0.0;
for (int i = -radius; i <= radius; i++) {
kernel[i + radius] = exp(-(i * i) / (2 * sigma * sigma)) / (sqrt(2 * PI) * sigma);
sum += kernel[i + radius];
}
for (int i = 0; i < 2 * radius + 1; i++) {
kernel[i] /= sum;
}
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
for (int c = 0; c < channels; c++) {
double sum = 0.0;
for (int i = -radius; i <= radius; i++) {
int x2 = x + i;
if (x2 < 0) {
x2 = 0;
}
if (x2 >= width) {
x2 = width - 1;
}
sum += kernel[i + radius] * image[(y * width + x2) * channels + c];
}
output_image[(y * width + x) * channels + c] = (unsigned char)sum;
}
}
}
stbi_write_png(output_filename, width, height, channels, output_image, width * channels);
stbi_image_free(image);
free(output_image);
free(kernel);
return 0;
}
```
这份代码使用了STB库来读取和写入图像,需要在代码中包含stb_image.h和stb_image_write.h头文件。高斯模糊的核函数是一个一维的高斯分布,代码中使用了一个数组来存储这个核函数。对于每个像素,代码将核函数应用于其周围的像素,得到模糊后的像素值。最后,代码使用STB库将输出图像写入文件。
注意,这份代码中的卷积操作是一维的,因此需要对每个通道分别进行卷积。如果需要进行二维的高斯模糊,可以将一维的核函数在两个方向上分别应用。
阅读全文