上一篇我们介绍了X264的编码,但是只能对本地文件编码,这里讨论怎么实时的读取摄像头文件并编码。
利用opencv实时读取摄像头,可以参考博客:点击打开链接。这里不做过多介绍。
至于编码流程,和上篇一样,没有改变。我们了解下X264编码器怎么直接读取摄像头的一帧图像就行。
opencv打开摄像头时,一帧一帧的播放,每一帧都由frame指定:capture >> frame
当然这里还有问题,X264对输入的要求是YUV格式,但是经过opencv采集后一帧frame是RGB格式,所以在编码之前我们要先将格式转换下,利用opencv自带的函数cvtColor。
cv::cvtColor(frame, yuvImg, CV_BGR2YUV_I420)
函数原型:
void cvCvtColor(const CvArr* src,CvArr* dst,int code) src:输入; dst:输出; code:转换的模式;
转换后的数据保存在yuvImg中,并通过fwrite函数写出,这里写出的数据是YUV格式,直接将其送到X264编码器的接口处就能开始编码。
最后给出完整代码:
#include
#include
#include
#include
#include "stdafx.h"
#include "stdint.h"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
extern "C"
{
#include "x264.h"
#include "x264_config.h"
};
using namespace cv;
using namespace std;
int MyYuvtoH264(int width, int height, string filename)
{
int fps = 25;
size_t yuv_size =