文章目录

一、简单读取

头文件 ​​quick_opencv.h​​:声明类与公共函数

#pragma once
#include <opencv2\opencv.hpp>
using namespace cv;

class QuickDemo {
public:
...
void video_Demo(Mat& image);
};

主函数调用该类的公共成员函数

#include <opencv2\opencv.hpp>
#include <quick_opencv.h>
#include <iostream>
using namespace cv;


int main(int argc, char** argv) {
Mat src = imread("D:\\Desktop\\pandas.jpg");
if (src.empty()) {
printf("Could not load images...\n");
return -1;
}
namedWindow("input", WINDOW_NORMAL);
imshow("input", src);

QuickDemo qk;

...
//qk.polyline_drawing_Demo();
qk.video_Demo(src);
waitKey(0);
destroyAllWindows();
return 0;
}

源文件 ​​quick_demo.cpp​​:实现类与公共函数

void QuickDemo::video_Demo(Mat& image) {
VideoCapture captrue("D\\balltest.mp4"); //打开视频
//VideoCapture captrue(0); //打开相机
Mat frame;
while (true)
{
captrue.read(frame);
if (frame.empty()) {
break;
}
// TODO:各种处理
imshow("frame", frame);
int c = waitKey(10);
if (c == 27) {
break;
}
}
captrue.release();
}

二、视频属性


VideoWriter::VideoWriter(
const String & filename,   视频文件的路径名称
int fourcc,        表示用于编码视频文件的编码器
double fps,         帧率
Size frameSize,       帧宽高
bool isColor=true     灰度图像或者是彩色图像(仅仅在windows上支持)
)


  • fourcc为 四个字符用来表示压缩帧的codec 例如:
    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
    若编码器代号为 -1,则运行时会弹出一个编码器选择框.
void QuickDemo::video_Demo(Mat& image) {
VideoCapture captrue("D:\\opencv-c++\\images\\balltest.mp4"); //打开视频
int frame_width = captrue.get(CAP_PROP_FRAME_WIDTH); // 帧宽
int frame_height = captrue.get(CAP_PROP_FRAME_HEIGHT); // 帧高
int count = captrue.get(CAP_PROP_FRAME_COUNT); // 总帧数
double fps = captrue.get(CAP_PROP_FPS); // 帧率

std::cout<< "frame_width=" << frame_width << std::endl;
std::cout<< "frame_height=" << frame_height << std::endl;
std::cout<< "Number of frames count=" << count << std::endl;
std::cout<< "FPS=" << fps << std::endl;

VideoWriter writer("D:\\Desktop\\test.mp4", captrue.get(CAP_PROP_FOURCC),fps,Size(frame_width,frame_height),true);
Mat frame, hsv;
while (true)
{
captrue.read(frame);
if (frame.empty()) {
break;
}
// TODO:各种处理
cvtColor(frame, hsv, COLOR_BGR2HSV);
imshow("hsv", hsv);

writer.write(hsv);
int c = waitKey(10);
if (c == 27) {
break;
}
}
captrue.release();
writer.release();
}