单色位图均值滤波C++代码实现
时间: 2023-10-25 09:13:57 浏览: 84
利用纯C语言解析单色位图文件获取颜色值的代码
以下是单色位图均值滤波的C代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BMP_HEADER_SIZE 54
#define PIXEL_OFFSET 10
#define BITS_PER_PIXEL_OFFSET 28
int width;
int height;
int padding;
unsigned char* bmp_data;
void read_bmp(char* filename) {
FILE* file = fopen(filename, "rb");
if (!file) {
printf("Error: File not found\n");
exit(1);
}
unsigned char header[BMP_HEADER_SIZE];
fread(header, sizeof(unsigned char), BMP_HEADER_SIZE, file);
width = *(int*)&header[18];
height = *(int*)&header[22];
padding = (4 - (width * 3) % 4) % 4;
bmp_data = (unsigned char*)malloc(sizeof(unsigned char) * (height * width * 3 + height * padding));
fseek(file, PIXEL_OFFSET, SEEK_SET);
fread(bmp_data, sizeof(unsigned char), height * width * 3 + height * padding, file);
fclose(file);
}
void write_bmp(char* filename, unsigned char* data) {
FILE* file = fopen(filename, "wb");
if (!file) {
printf("Error: Cannot write to file\n");
exit(1);
}
unsigned char header[BMP_HEADER_SIZE];
memset(header, 0, BMP_HEADER_SIZE);
header[0] = 'B';
header[1] = 'M';
*(int*)&header[2] = BMP_HEADER_SIZE + width * height * 3 + height * padding;
header[10] = BMP_HEADER_SIZE;
*(int*)&header[18] = width;
*(int*)&header[22] = height;
header[26] = 1;
header[28] = 24;
fwrite(header, sizeof(unsigned char), BMP_HEADER_SIZE, file);
fwrite(data, sizeof(unsigned char), height * width * 3 + height * padding, file);
fclose(file);
}
void apply_filter(unsigned char* data) {
unsigned char* temp_data = (unsigned char*)malloc(sizeof(unsigned char) * (height * width * 3 + height * padding));
memcpy(temp_data, data, sizeof(unsigned char) * (height * width * 3 + height * padding));
for (int i = 1; i < height - 1; i++) {
for (int j = 1; j < width - 1; j++) {
int sum_r = 0, sum_g = 0, sum_b = 0;
for (int k = -1; k <= 1; k++) {
for (int l = -1; l <= 1; l++) {
sum_r += temp_data[((i + k) * width + (j + l)) * 3 + 2];
sum_g += temp_data[((i + k) * width + (j + l)) * 3 + 1];
sum_b += temp_data[((i + k) * width + (j + l)) * 3];
}
}
data[(i * width + j) * 3 + 2] = sum_r / 9;
data[(i * width + j) * 3 + 1] = sum_g / 9;
data[(i * width + j) * 3] = sum_b / 9;
}
}
free(temp_data);
}
int main() {
read_bmp("input.bmp");
apply_filter(bmp_data);
write_bmp("output.bmp", bmp_data);
free(bmp_data);
return 0;
}
```
阅读全文