// 将 NV12 转换为 BGR void nv12ToBgr(const unsigned char* yuvData, int width, int height, Mat& bgrImage) {// 计算每个平面的大小int ySize = width * height;int uvSize = (width / 2) * (height / 2);// 创建一个包含 NV12 数据的 Mat 对象Mat nv12(height + height / 2, width, CV_8UC1, const_cast<unsigned char*>(yuvData));// 直接使用 OpenCV 的颜色转换函数进行 NV12 到 BGR 的转换cvtColor(nv12, bgrImage, COLOR_YUV2BGR_NV12); }
#include <opencv2/opencv.hpp> #include <iostream> #include <fstream> #include <vector>using namespace std; using namespace cv;// 将 NV12 转换为 BGR void nv12ToBgr(const unsigned char* yuvData, int width, int height, Mat& bgrImage) {// 计算每个平面的大小int ySize = width * height;int uvSize = (width / 2) * (height / 2);// 创建一个包含 NV12 数据的 Mat 对象Mat nv12(height + height / 2, width, CV_8UC1, const_cast<unsigned char*>(yuvData));// 直接使用 OpenCV 的颜色转换函数进行 NV12 到 BGR 的转换cvtColor(nv12, bgrImage, COLOR_YUV2BGR_NV12); }int main() {// OpenCV 版本号cout << "OpenCV_Version: " << CV_VERSION << endl;string filePath = "f.nv12";ifstream file(filePath, ios::binary | ios::ate);if (!file.is_open()) {cerr << "无法打开文件: " << filePath << endl;return -1;}streamsize size = file.tellg();file.seekg(0, ios::beg);vector<char> buffer(size);if (!file.read(buffer.data(), size)) {cerr << "无法读取文件: " << filePath << endl;return -1;}int width = 640; // 假设宽度为 640int height = 480; // 假设高度为 480Mat bgrImage;nv12ToBgr(reinterpret_cast<const unsigned char*>(buffer.data()), width, height, bgrImage);// 显示图像imshow("NV12 to BGR", bgrImage);waitKey(0);return 0; }