show image, convert yuv to rgb by opencv

下面程序读取camera.yuv ,然后使用Mat 保存,再用cv:cvtColoryuv 数据转化成rgb显示

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
55
56
57

#include <fstream>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

const int width = 1920;
const int height = 1080;
const int framesize = width * height * 3 / 2;
using namespace std;
using namespace cv;
int ()
{
ifstream fin;
fin.open("camera.yuv", ios_base::in | ios_base::binary);
if (fin.fail())
{
cout << "the file is error" << endl;
return -1;
}

fin.seekg(0, ios::end);
streampos ps = fin.tellg();//指出当前的文件指针  
unsigned long NumberPixe = ps;
cout << "file size: " << ps << endl;//输出指针的位置  
unsigned FrameCount = ps / framesize; //帧大小  
cout << "frameNuber: " << FrameCount; //输出帧数  
fin.close();
FILE* fileIn = fopen("camera.yuv", "rb+");
unsigned char* pYuvBuf = new unsigned char[framesize]; //一帧数据大小

//存储到图像  
cv::namedWindow("yuv", 1);

for (int i = 0; i < FrameCount; ++i)
{
fread(pYuvBuf, framesize * sizeof(unsigned char), 1, fileIn);
cv::Mat yuvImg;
yuvImg.create(height * 3 / 2, width, CV_8UC1);
memcpy(yuvImg.data, pYuvBuf, framesize * sizeof(unsigned char));
cv::Mat rgbImg;
cv::cvtColor(yuvImg, rgbImg, CV_YUV2BGR_I420);

cv::imshow("yuv", yuvImg); //只显示y分量
cv::imshow("rgbImg", rgbImg);

printf("第 %d 帧n", i);
int c = waitKey(10000);
if ((char)c == 27)
{
break;
}
}
fclose(fileIn);
cvDestroyWindow("yuv");
}