将灰度图像转为rgb图像 的C 语言代码
时间: 2024-05-09 14:21:32 浏览: 9
以下是将灰度图像转为RGB图像的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp_in, *fp_out;
int width, height, max_gray;
unsigned char *gray_img, *rgb_img;
char *file_in = "gray_img.pgm";
char *file_out = "rgb_img.ppm";
// 打开灰度图像文件
fp_in = fopen(file_in, "rb");
if (fp_in == NULL) {
printf("Error: cannot open %s\n", file_in);
exit(1);
}
// 读取灰度图像的宽度、高度和最大灰度值
fscanf(fp_in, "P5\n%d %d\n%d\n", &width, &height, &max_gray);
// 分配内存并读取灰度图像数据
gray_img = (unsigned char *)malloc(width * height * sizeof(unsigned char));
fread(gray_img, sizeof(unsigned char), width * height, fp_in);
// 关闭灰度图像文件
fclose(fp_in);
// 分配内存并转换为RGB图像数据
rgb_img = (unsigned char *)malloc(width * height * 3 * sizeof(unsigned char));
for (int i = 0; i < width * height; i++) {
rgb_img[i * 3] = gray_img[i];
rgb_img[i * 3 + 1] = gray_img[i];
rgb_img[i * 3 + 2] = gray_img[i];
}
// 打开RGB图像文件
fp_out = fopen(file_out, "wb");
if (fp_out == NULL) {
printf("Error: cannot create %s\n", file_out);
exit(1);
}
// 写入PPM文件头
fprintf(fp_out, "P6\n%d %d\n%d\n", width, height, max_gray);
// 写入RGB图像数据
fwrite(rgb_img, sizeof(unsigned char), width * height * 3, fp_out);
// 关闭RGB图像文件
fclose(fp_out);
// 释放内存
free(gray_img);
free(rgb_img);
return 0;
}
```
希望能帮到你!