c语言实现bmp文件的二值化代码
时间: 2024-05-05 13:20:11 浏览: 132
以下是一个简单的C语言实现bmp文件的二值化代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma pack(2)
typedef struct tagBITMAPFILEHEADER {
unsigned short bfType;
unsigned int bfSize;
unsigned short bfReserved1;
unsigned short bfReserved2;
unsigned int bfOffBits;
} BITMAPFILEHEADER;
typedef struct tagBITMAPINFOHEADER {
unsigned int biSize;
int biWidth;
int biHeight;
unsigned short biPlanes;
unsigned short biBitCount;
unsigned int biCompression;
unsigned int biSizeImage;
int biXPelsPerMeter;
int biYPelsPerMeter;
unsigned int biClrUsed;
unsigned int biClrImportant;
} BITMAPINFOHEADER;
typedef struct tagRGBQUAD {
unsigned char rgbBlue;
unsigned char rgbGreen;
unsigned char rgbRed;
unsigned char rgbReserved;
} RGBQUAD;
typedef struct tagBITMAP {
BITMAPFILEHEADER fileHeader;
BITMAPINFOHEADER infoHeader;
RGBQUAD *palette;
unsigned char *data;
} BITMAP;
void binarize(BITMAP *bmp) {
int i, j;
unsigned char *p = bmp->data;
for (i = 0; i < bmp->infoHeader.biHeight; i++) {
for (j = 0; j < bmp->infoHeader.biWidth; j++) {
// 获取像素值
unsigned char b = *p++;
unsigned char g = *p++;
unsigned char r = *p++;
// 灰度化
unsigned char gray = (unsigned char)(0.299 * r + 0.587 * g + 0.114 * b);
// 二值化
if (gray >= 128) {
*p++ = 255;
*p++ = 255;
*p++ = 255;
} else {
*p++ = 0;
*p++ = 0;
*p++ = 0;
}
}
}
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <bmp_file>\n", argv[0]);
return 1;
}
char *filename = argv[1];
FILE *fp = fopen(filename, "rb");
if (!fp) {
printf("Failed to open file: %s\n", filename);
return 1;
}
BITMAP bmp;
memset(&bmp, 0, sizeof(BITMAP));
fread(&bmp.fileHeader, sizeof(BITMAPFILEHEADER), 1, fp);
fread(&bmp.infoHeader, sizeof(BITMAPINFOHEADER), 1, fp);
if (bmp.infoHeader.biBitCount < 24) {
bmp.palette = (RGBQUAD *)malloc(sizeof(RGBQUAD) * (1 << bmp.infoHeader.biBitCount));
fread(bmp.palette, sizeof(RGBQUAD), 1 << bmp.infoHeader.biBitCount, fp);
}
bmp.data = (unsigned char *)malloc(bmp.infoHeader.biSizeImage);
fread(bmp.data, 1, bmp.infoHeader.biSizeImage, fp);
fclose(fp);
binarize(&bmp);
char *out_filename = "output.bmp";
fp = fopen(out_filename, "wb");
if (!fp) {
printf("Failed to create file: %s\n", out_filename);
return 1;
}
fwrite(&bmp.fileHeader, sizeof(BITMAPFILEHEADER), 1, fp);
fwrite(&bmp.infoHeader, sizeof(BITMAPINFOHEADER), 1, fp);
if (bmp.infoHeader.biBitCount < 24) {
fwrite(bmp.palette, sizeof(RGBQUAD), 1 << bmp.infoHeader.biBitCount, fp);
}
fwrite(bmp.data, 1, bmp.infoHeader.biSizeImage, fp);
fclose(fp);
free(bmp.palette);
free(bmp.data);
return 0;
}
```
该代码假设输入文件是24位(即每个像素由3个字节组成)的bmp文件,输出文件格式与输入文件相同,二值化算法为简单的阈值分割法。
阅读全文