利用opencv对视频剪辑,剪辑成任意四边形

对视频中每一帧图片进行剪辑,定义四边形各个顶点,输出剪辑后的视频,程序思想很简单,没有优化。

不解释了,上代码吧

#include "opencv2/opencv.hpp"
#include <iostream>
#include <vector>

using namespace std;
using namespace cv;

int main(int argc, char *argv[])
{
	const string file = "D:/Photo and Video/down.mp4";
	VideoCapture inputVideo(file);

	if (!inputVideo.isOpened())
	{
		cout << "Could not open the input video for write: " << endl;
		return -1;
	}


	//make a video writer and initialize it at 30 FPS
	VideoWriter outputVideo;
	outputVideo.open("1.mpg", CV_FOURCC('M', 'P', 'E', 'G'), 30, Size(900, 600), true);
	if (!outputVideo.isOpened())
	{
		cout << "Could not open the output video for write: " << endl;
		return -1;
	}
	namedWindow("video");
	namedWindow("crop_video");


	while (char(waitKey(1)) != 'q' && inputVideo.isOpened())
	{
		Mat frame;
		inputVideo >> frame;
		// check if video is over
		if (frame.empty())
		{
			cout << "video over" << endl;
			break;
		}
		int new_w = 0;
		int new_h = 0;
		new_w = frame.cols;
		new_h = frame.rows;
		Rect rectROI(0, 0, new_w, new_h);
		Mat mask(new_h, new_w, CV_8UC1, cv::Scalar(0));

		//P1,P2,P3,P4为四边形四个顶点,具体坐标大小根据实际更改
		Point P1(0, 0);  
		Point P2(960, 0);
		Point P3(640, 720);
		Point P4(320, 720);
		vector< vector<Point> > co_ordinates;
		co_ordinates.push_back(vector<Point>());


		co_ordinates[0].push_back(P1);
		co_ordinates[0].push_back(P2);
		co_ordinates[0].push_back(P3);
		co_ordinates[0].push_back(P4);
		drawContours(mask, co_ordinates, 0, Scalar(255), CV_FILLED, 8);


		Mat srcROI = frame(rectROI);
		Mat dst1;


		srcROI.copyTo(dst1, mask);

		outputVideo << dst1;
		imshow("video", frame);
		imshow("crop_video", dst1);

	}

	return 0;
}

剪辑后视频图片如下:

猜你喜欢

转载自blog.csdn.net/huoguangyao/article/details/84138979