c语言sauvola算法
时间: 2023-08-24 18:10:41 浏览: 43
Sauvola算法是一种局部自适应二值化算法,适用于文档图像二值化。下面是一个用C语言实现Sauvola二值化算法的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define WIDTH 512
#define HEIGHT 512
typedef unsigned char BYTE;
BYTE InputImg[WIDTH][HEIGHT]; // 输入图像
BYTE OutputImg[WIDTH][HEIGHT]; // 输出图像
// 计算局部均值和标准差
void calcuMeanStd(int x, int y, int w, int h, double *mean, double *std) {
int i, j;
double Sum = 0.0, SqSum = 0.0;
for (i = x; i < x + w; i++) {
for (j = y; j < y + h; j++) {
Sum += InputImg[i][j];
SqSum += InputImg[i][j] * InputImg[i][j];
}
}
*mean = Sum / (w * h);
*std = sqrt((SqSum - Sum * Sum / (w * h)) / (w * h));
}
// Sauvola二值化算法
void Sauvola() {
int i, j;
double k = 0.5, R = 128.0;
double mean, std, threshold;
for (i = 0; i < WIDTH; i++) {
for (j = 0; j < HEIGHT; j++) {
calcuMeanStd(i - 5, j - 5, 11, 11, &mean, &std);
threshold = mean * (1 + k * (std / R - 1));
OutputImg[i][j] = InputImg[i][j] > threshold ? 255 : 0;
}
}
}
// 读取灰度图像
void readGrayImage(char *filename) {
FILE *fp;
if ((fp = fopen(filename, "rb")) == NULL) {
printf("Open file error!\n");
exit(-1);
}
fread(InputImg, sizeof(BYTE), WIDTH * HEIGHT, fp);
fclose(fp);
}
// 写入灰度图像
void writeGrayImage(char *filename) {
FILE *fp;
if ((fp = fopen(filename, "wb")) == NULL) {
printf("Open file error!\n");
exit(-1);
}
fwrite(OutputImg, sizeof(BYTE), WIDTH * HEIGHT, fp);
fclose(fp);
}
int main() {
char *input = "input.raw";
char *output = "output.raw";
readGrayImage(input);
Sauvola();
writeGrayImage(output);
return 0;
}
```
该代码中,calcMeanStd函数用于计算局部均值和标准差,Sauvola函数实现Sauvola二值化算法,readGrayImage函数读取灰度图像,writeGrayImage函数写入灰度图像。在main函数中,将输入图像读入InputImg数组中,调用Sauvola函数实现二值化,将输出图像写入OutputImg数组中。最后,将输出图像保存在output.raw文件中。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)