用c语言写一段对图片进行灰度处理的代码
时间: 2024-05-04 18:15:32 浏览: 59
好的,以下是示例代码:
```
#include <stdio.h>
int main() {
FILE *fp;
char buf[54];
int width, height, rawSize;
unsigned char *rawData;
// Open image file
fp = fopen("image.bmp", "rb");
if (!fp) {
printf("Error: Failed to open image file!\n");
return 1;
}
// Read BMP header
fread(buf, sizeof(char), 54, fp);
width = *(int*)&buf[18];
height = *(int*)&buf[22];
rawSize = *(int*)&buf[34];
// Allocate memory for raw data
rawData = (unsigned char*)malloc(rawSize);
// Read raw data
fread(rawData, sizeof(unsigned char), rawSize, fp);
// Close image file
fclose(fp);
// Convert to grayscale
for (int i = 0; i < rawSize; i += 3) {
unsigned char gray = (unsigned char)(0.299 * rawData[i+2] + 0.587 * rawData[i+1] + 0.114 * rawData[i]);
rawData[i+2] = rawData[i+1] = rawData[i] = gray;
}
// Open output image file
fp = fopen("grayscale.bmp", "wb");
if (!fp) {
printf("Error: Failed to create output image file!\n");
return 1;
}
// Write BMP header and raw data
fwrite(buf, sizeof(char), 54, fp);
fwrite(rawData, sizeof(unsigned char), rawSize, fp);
// Close output image file
fclose(fp);
// Free memory
free(rawData);
printf("Grayscale conversion completed!\n");
return 0;
}
```
该代码使用了 BMP 文件格式来存储图像数据,并且只能处理 24 位彩色位图。将 RGB 三个颜色通道按比例加权求和即可转换为灰度值。
阅读全文