opencv转换NV12到Mat格式代码
时间: 2023-12-11 17:05:50 浏览: 339
下面是将NV12转换成Mat的OpenCV代码示例:
```cpp
// 将NV12数据转换为Mat格式
cv::Mat nv12ToMat(const uint8_t* data, int width, int height)
{
cv::Mat yuv(height + height / 2, width, CV_8UC1, (uchar*)data);
cv::Mat bgr;
cv::cvtColor(yuv, bgr, cv::COLOR_YUV2BGR_NV12);
return bgr;
}
```
其中,`data`是NV12数据的指针,`width`和`height`是图像的宽度和高度。函数返回的是转换后的Mat格式图像。
需要注意的是,NV12是一种YUV格式,其中Y和UV数据是交错存储的。在将NV12数据转换为Mat格式前,需要先将其转换为YUV格式,然后再使用OpenCV提供的`cvtColor`函数将其转换为BGR格式。
相关问题
使用opencv把NV12转换为Mat格式代码示例
下面是一个使用OpenCV将NV12数据转换为Mat格式的代码示例:
```cpp
#include <opencv2/opencv.hpp>
// 将NV12数据转换为Mat格式
cv::Mat nv12ToMat(const uint8_t* data, int width, int height)
{
cv::Mat yuv(height + height / 2, width, CV_8UC1, (uchar*)data);
cv::Mat bgr;
cv::cvtColor(yuv, bgr, cv::COLOR_YUV2BGR_NV12);
return bgr;
}
int main()
{
// 读取NV12数据
FILE* fp = fopen("test.nv12", "rb");
fseek(fp, 0, SEEK_END);
int size = ftell(fp);
fseek(fp, 0, SEEK_SET);
uint8_t* data = new uint8_t[size];
fread(data, size, 1, fp);
fclose(fp);
// 转换为Mat格式
int width = 640;
int height = 480;
cv::Mat mat = nv12ToMat(data, width, height);
// 显示图像
cv::imshow("Image", mat);
cv::waitKey(0);
// 释放内存
delete[] data;
return 0;
}
```
其中,`test.nv12`是NV12格式的文件,可以使用工具生成。函数`nv12ToMat`将NV12数据转换为Mat格式,然后在主函数中读取NV12数据,转换为Mat格式,并显示图像。需要注意的是,NV12格式的数据大小应该是`1.5 * width * height`。
使用opencv把NV12转换为BGR格式代码示例
下面是一个使用OpenCV将NV12数据转换为BGR格式的代码示例:
```cpp
#include <opencv2/opencv.hpp>
// 将NV12数据转换为BGR格式
void nv12ToBgr(const uint8_t* data, int width, int height, uint8_t* bgr)
{
cv::Mat yuv(height + height / 2, width, CV_8UC1, (uchar*)data);
cv::Mat bgrMat(height, width, CV_8UC3, bgr);
cv::cvtColor(yuv, bgrMat, cv::COLOR_YUV2BGR_NV12);
}
int main()
{
// 读取NV12数据
FILE* fp = fopen("test.nv12", "rb");
fseek(fp, 0, SEEK_END);
int size = ftell(fp);
fseek(fp, 0, SEEK_SET);
uint8_t* data = new uint8_t[size];
fread(data, size, 1, fp);
fclose(fp);
// 转换为BGR格式
int width = 640;
int height = 480;
uint8_t* bgr = new uint8_t[width * height * 3];
nv12ToBgr(data, width, height, bgr);
// 保存图像
cv::Mat bgrMat(height, width, CV_8UC3, bgr);
cv::imwrite("output.jpg", bgrMat);
// 释放内存
delete[] data;
delete[] bgr;
return 0;
}
```
其中,`test.nv12`是NV12格式的文件,可以使用工具生成。函数`nv12ToBgr`将NV12数据转换为BGR格式,并将结果保存在`bgr`指向的内存中。在主函数中读取NV12数据,转换为BGR格式,并保存图像。需要注意的是,NV12格式的数据大小应该是`1.5 * width * height`,而BGR格式的数据大小应该是`3 * width * height`。
阅读全文
相关推荐













