VS2015+OPENCV4.1.1读取视频并保存
vs2015配置opencv4.1.1请看我的另一篇文章:https://blog.csdn.net/l641208111/article/details/99929961
代码如下:
#include
#include
#include "opencv2/highgui/highgui_c.h"
#include "opencv2/imgproc/imgproc_c.h"
using namespace cv;
using namespace std;
int main()
{
VideoCapture capture;
capture.open(0);
if (!capture.isOpened())
{
printf("can not open ...\n");
return -1;
}
Size size = Size(capture.get(CAP_PROP_FRAME_WIDTH), capture.get(CAP_PROP_FRAME_HEIGHT));//CAP_OPENCV_MJPEG
VideoWriter writer;
writer.open("./my1.AVI", writer.fourcc('M', 'J', 'P', 'G'), 10, size, true);//CAP_OPENCV_MJPEG
Mat frame, gray;
namedWindow("output", CV_WINDOW_AUTOSIZE);
while (capture.read(frame))
{
//转换为黑白图像
cvtColor(frame, gray, COLOR_BGR2GRAY);
//二值化处理
threshold(gray, gray, 0, 255, THRESH_BINARY | THRESH_OTSU);
cvtColor(gray, gray, COLOR_GRAY2BGR);
imshow("output", gray);
writer.write(gray);
waitKey(10);
}
waitKey(0);
capture.release();
return 0;
}
出现的问题:
1、保存的视频无法打开
方法:这是由于OpenCV中CV_FOURCC的编码方式决定的;
CV_FOURCC('P', 'I', 'M', '1') = MPEG-1 codec
CV_FOURCC('M', 'J', 'P', 'G') = motion-jpeg codec
CV_FOURCC('M', 'P', '4', '2') = MPEG-4.2 codec
CV_FOURCC('D', 'I', 'V', '3') = MPEG-4.3 codec
CV_FOURCC('D', 'I', 'V', 'X') = MPEG-4 codec
CV_FOURCC('U', '2', '6', '3') = H263 codec
CV_FOURCC('I', '2', '6', '3') = H263I codec
CV_FOURCC('F', 'L', 'V', '1') = FLV1 codec
例子中用的编码方式是CV_FOURCC('M', 'J', 'P', 'G')(OPENCV3版本以下), opencv4版本应为writer.fourcc('M', 'J', 'P', 'G'),
视频格式保存为.avi方式就可以了。
…