gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
使用C语言将NV12图片转换成数组
- User
使用C语言将NV12图片转换成数组
- Assistant
以下是使用C语言将NV12图片转换成数组的示例代码:
#include <stdio.h> #include <stdlib.h> #define WIDTH 640 #define HEIGHT 480 int main() { FILE *infile = fopen("input.yuv", "rb"); if (!infile) { printf("Failed to open input file.\n"); return -1; } /* Allocate memory for YUV frames */ unsigned char *yuv_data = (unsigned char *)malloc((WIDTH * HEIGHT * 3) / 2); unsigned char *y_data = yuv_data; unsigned char *vu_data = yuv_data + WIDTH * HEIGHT; /* Read YUV data from file */ fread(yuv_data, sizeof(unsigned char), (WIDTH * HEIGHT * 3) / 2, infile); /* Allocate memory for RGB frames */ unsigned char *rgb_data = (unsigned char *)malloc(WIDTH * HEIGHT * 3); unsigned char *r_data = rgb_data; unsigned char *g_data = rgb_data + WIDTH * HEIGHT; unsigned char *b_data = rgb_data + WIDTH * HEIGHT * 2; /* Convert YUV to RGB */ int i, j, y, u, v, r, g, b; for (i = 0; i < HEIGHT; i++) { for (j = 0; j < WIDTH; j++) { y = y_data[i * WIDTH + j]; u = vu_data[(i / 2) * (WIDTH / 2) * 2 + (j / 2) * 2]; v = vu_data[(i / 2) * (WIDTH / 2) * 2 + (j / 2) * 2 + 1]; r = y + (1.370705 * (v - 128)); g = y - (0.698001 * (v - 128)) - (0.337633 * (u - 128)); b = y + (1.732446 * (u - 128)); if (r < 0) r = 0; if (g < 0) g = 0; if (b < 0) b = 0; if (r > 255) r = 255; if (g > 255) g = 255; if (b > 255) b = 255; r_data[i * WIDTH + j] = r; g_data[i * WIDTH + j] = g; b_data[i * WIDTH + j] = b; } } /* Print RGB values as array */ printf("unsigned char rgb_array[%d][%d][3] = {\n", HEIGHT, WIDTH); for (i = 0; i < HEIGHT; i++) { printf(" {\n"); for (j = 0; j < WIDTH; j++) { printf(" {%d, %d, %d}", r_data[i * WIDTH + j], g_data[i * WIDTH + j], b_data[i * WIDTH + j]); if (j != WIDTH - 1) printf(","); printf("\n"); } printf(" }"); if (i != HEIGHT - 1) printf(","); printf("\n"); } printf("};\n"); /* Free memory */ free(yuv_data); free(rgb_data); fclose(infile); return 0; }这个示例代码假设输入文件是名为"input.yuv"的NV12格式图像。它首先读取YUV数据,并将其转换为RGB格式。然后,它将RGB值存储在一个名为“rgb_array”的三维unsigned char数组中,并将其打印出来以便将其复制到C代码中。最后,它释放了所分配的内存并关闭了输入文件。
请注意,这里实现的RGB转换算法是基于ITU-R BT.601标准并不是最优的算法,你可以根据自己需要使用更好的算法。
- User
makefile编译.c文件
- Assistant
以下是一个简单的makefile,用于编译.c文件:
# 定义编译器 CC = gcc # 定义编译选项 CFLAGS = -Wall -Wextra -Werror # 定义源文件 SRCS = main.c file1.c file2.c # 定义目标文件 OBJS = $(SRCS:.c=.o) # 定义可执行文件名 TARGET = my_program all: $(TARGET) $(TARGET): $(OBJS) $(CC) $(CFLAGS) $(OBJS) -o $(TARGET) %.o: %.c $(CC) $(CFLAGS) -c $< -o $@ clean: $(RM) $(OBJS) $(TARGET) .PHONY: all clean在这个makefile中:
- 编译器被定义为gcc。
- 编译选项被定义为-Wall、-Wextra和-Werror,其中-Wall表示启用所有警告,-Wextra表示启用额外的警告,-Werror表示将警告视为错误。
- 源文件被定义为main.c、file1.c和file2.c,可以根据需要添加或删除源文件。
- 目标文件被定义为$(SRCS:.c=.o),这将.c后缀的源文件转换为.o后缀的目标文件。
- 可执行文件的名称被定义为my_program。
- all是默认目标,它依赖于$(TARGET)。
- (OBJS),在这个规则中,(OBJS)链接为可执行文件$(TARGET)。
- $(OBJS)的每个元素作为依赖项生成对应的目标文件。
- clean是用于删除目标文件和可执行文件的目标,它依赖于(TARGET)。
- .PHONY告诉make,all和clean是伪目标,而不是实际文件。