写一段linux下bmp转yuv420的C语言代码
时间: 2024-05-10 09:19:04 浏览: 179
rgb转yuv420源代码(C语言)
4星 · 用户满意度95%
以下是一段简单的 Linux 下 BMP 转 YUV420 的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BMP_HEADER_SIZE 54
void bmp_to_yuv420(char *bmp_file, char *yuv_file, int width, int height) {
FILE *bmp_fp = fopen(bmp_file, "rb");
if (bmp_fp == NULL) {
printf("Failed to open BMP file.\n");
return;
}
FILE *yuv_fp = fopen(yuv_file, "wb");
if (yuv_fp == NULL) {
printf("Failed to create YUV file.\n");
fclose(bmp_fp);
return;
}
// BMP header
unsigned char bmp_header[BMP_HEADER_SIZE];
fread(bmp_header, sizeof(unsigned char), BMP_HEADER_SIZE, bmp_fp);
// Image data
int image_size = width * height * 3;
unsigned char *image_data = (unsigned char *)malloc(image_size * sizeof(unsigned char));
fread(image_data, sizeof(unsigned char), image_size, bmp_fp);
// YUV data
int y_size = width * height;
int u_size = y_size / 4;
int v_size = y_size / 4;
unsigned char *yuv_data = (unsigned char *)malloc((y_size + u_size + v_size) * sizeof(unsigned char));
// Convert BMP to YUV
int i, j, k, l;
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
int index = i * width + j;
int y_index = i * width + j;
int u_index = (i / 2) * (width / 2) + (j / 2) + y_size;
int v_index = (i / 2) * (width / 2) + (j / 2) + y_size + u_size;
unsigned char r = image_data[index * 3];
unsigned char g = image_data[index * 3 + 1];
unsigned char b = image_data[index * 3 + 2];
// Y component
yuv_data[y_index] = (unsigned char)(0.299 * r + 0.587 * g + 0.114 * b);
// U component
if (i % 2 == 0 && j % 2 == 0) {
int u_sum = 0;
for (k = i; k < i + 2; k++) {
for (l = j; l < j + 2; l++) {
int u_index = (k / 2) * (width / 2) + (l / 2) + y_size;
u_sum += image_data[(k * width + l) * 3 + 1];
}
}
yuv_data[u_index] = (unsigned char)(u_sum / 4);
}
// V component
if (i % 2 == 0 && j % 2 == 0) {
int v_sum = 0;
for (k = i; k < i + 2; k++) {
for (l = j; l < j + 2; l++) {
int v_index = (k / 2) * (width / 2) + (l / 2) + y_size + u_size;
v_sum += image_data[(k * width + l) * 3 + 2];
}
}
yuv_data[v_index] = (unsigned char)(v_sum / 4);
}
}
}
// Write YUV file
fwrite(yuv_data, sizeof(unsigned char), y_size + u_size + v_size, yuv_fp);
// Cleanup
free(image_data);
free(yuv_data);
fclose(bmp_fp);
fclose(yuv_fp);
}
int main() {
bmp_to_yuv420("input.bmp", "output.yuv", 640, 480);
return 0;
}
```
这段代码会将输入的 BMP 文件转换为 YUV420 格式,并将结果保存到指定的 YUV 文件中。需要注意的是,这段代码仅适用于 24 位真彩色 BMP 图像。如果要处理其他类型的 BMP 图像,需要对代码进行适当的修改。
阅读全文