NV12数据转OpenCV的Mat

1
2
3
4
5
6
7
8
9
10
11
12
// 将 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);
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#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;  // 假设宽度为 640
    int height = 480; // 假设高度为 480
 
    Mat bgrImage;
    nv12ToBgr(reinterpret_cast<const unsigned char*>(buffer.data()), width, height, bgrImage);
 
    // 显示图像
    imshow("NV12 to BGR", bgrImage);
    waitKey(0);
 
    return 0;
}

  

posted @   ahuo  阅读(122)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2018-12-20 ssh 多次登录禁用账号
2016-12-20 docker使用GPU
点击右上角即可分享
微信分享提示