基于C语言的高斯模糊代码和解释
时间: 2023-05-19 21:04:26 浏览: 255
高斯模糊是一种常用的图像处理技术,可以用于图像降噪、模糊等应用。以下是基于C语言的高斯模糊代码和解释:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265358979323846
// 高斯函数
double gaussian(double x, double sigma) {
return exp(-x * x / (2 * sigma * sigma)) / (sigma * sqrt(2 * PI));
}
// 高斯模板生成
void gaussian_kernel(double *kernel, int size, double sigma) {
int center = size / 2;
double sum = 0;
for (int i = 0; i < size; i++) {
kernel[i] = gaussian(i - center, sigma);
sum += kernel[i];
}
for (int i = 0; i < size; i++) {
kernel[i] /= sum;
}
}
// 高斯模糊
void gaussian_blur(unsigned char *image, int width, int height, double sigma) {
int size = (int)(sigma * 6 + 1) | 1; // 根据sigma计算模板大小
double *kernel = (double *)malloc(size * sizeof(double)); // 生成高斯模板
gaussian_kernel(kernel, size, sigma);
unsigned char *temp = (unsigned char *)malloc(width * height * sizeof(unsigned char)); // 临时数组
// 水平方向模糊
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
double sum = 0;
for (int i = -size / 2; i <= size / 2; i++) {
int xx = x + i;
if (xx < 0) xx = 0;
if (xx >= width) xx = width - 1;
sum += kernel[i + size / 2] * image[y * width + xx];
}
temp[y * width + x] = (unsigned char)sum;
}
}
// 垂直方向模糊
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
double sum = 0;
for (int i = -size / 2; i <= size / 2; i++) {
int yy = y + i;
if (yy < 0) yy = 0;
if (yy >= height) yy = height - 1;
sum += kernel[i + size / 2] * temp[yy * width + x];
}
image[y * width + x] = (unsigned char)sum;
}
}
free(kernel);
free(temp);
}
int main() {
// 读取图像
FILE *fp = fopen("lena.raw", "rb");
unsigned char *image = (unsigned char *)malloc(512 * 512 * sizeof(unsigned char));
fread(image, sizeof(unsigned char), 512 * 512, fp);
fclose(fp);
// 高斯模糊
gaussian_blur(image, 512, 512, 10);
// 保存图像
fp = fopen("lena_blur.raw", "wb");
fwrite(image, sizeof(unsigned char), 512 * 512, fp);
fclose(fp);
free(image);
return 0;
}
```
这段代码实现了基于C语言的高斯模糊,通过调用`gaussian_blur`函数可以对图像进行高斯模糊处理。其中,`sigma`参数表示高斯函数的标准差,`size`参数表示高斯模板的大小,`kernel`数组表示高斯模板,`temp`数组表示临时数组。在水平方向和垂直方向分别进行模糊处理,最终得到模糊后的图像。