时间:2020-11-24 16:33:25 | 栏目:Python代码 | 点击:次
视频读取
视频读取,主要利用VideoCapture类下的方法打开视频并获取视频中的帧,具体示例如下:
#include<iostream> #include<opencv2/opencv.hpp> using namespace cv; int main() { VideoCapture capture; Mat frame; frame= capture.open("E:/image/a1.avi"); if(!capture.isOpened()) { printf("can not open ...\n"); return -1; } namedWindow("output", CV_WINDOW_AUTOSIZE); while (capture.read(frame)) { imshow("output", frame); waitKey(10); } capture.release(); return 0; }
capture.open()的参数为0时为读取摄像头:
frame= capture.open(0);
视频写入
通过摄像头获取视频,然后通过capture.get(CV_CAP_PROP_FRAME_WIDTH), capture.get(CV_CAP_PROP_FRAME_HEIGHT)获取当前帧的宽度和高度,创建一个VideoWriter类对象writer进行视频的写入。
写入前可进行视频的简单处理。
#include<iostream> #include<opencv2/opencv.hpp> using namespace cv; int main() { VideoCapture capture; capture.open(0); if(!capture.isOpened()) { printf("can not open ...\n"); return -1; } Size size = Size(capture.get(CV_CAP_PROP_FRAME_WIDTH), capture.get(CV_CAP_PROP_FRAME_HEIGHT)); VideoWriter writer; writer.open("E:/image/a2.avi", CV_FOURCC('M', 'J', 'P', 'G'), 10, size, true); 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; }