opencv读写视频,对感兴趣区域进行裁剪

时间:2023-03-08 22:17:24

作为小码农,本人最近想对一段视频的某个区域进行处理,因此要将该段视频区域裁剪出来,搜搜网上,发现没有痕迹,是故自己琢磨一下,左右借鉴,编了如下代码,目标得以实现,希望对你有用。

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

using namespace std;
using namespace cv;

int main(int argc, char *argv[])
{
	const string file = "C:\\Users\\helei\\Desktop\\people_flow\\one\\自动化所智能化大厦.MOV";
	VideoCapture inputVideo(file);

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

	//Get sizes of frames
	//Size S = Size(inputVideo.get(CV_CAP_PROP_FRAME_WIDTH),
	//	inputVideo.get(CV_CAP_PROP_FRAME_HEIGHT));

    //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");

	//ROI
	Rect box;
	box.width = 900;
	box.height = 600;
	box.x = 900;
	box.y = 300;

	while(char(waitKey(1)) != 'q' && inputVideo.isOpened())
    {
		Mat frame;
        inputVideo >> frame;
		// check if video is over
        if (frame.empty())
		{
			cout << "video over" << endl;
			break;
		}
		Mat crop(frame,box);
		outputVideo << crop;
		imshow("video",frame);
		imshow("crop_video",crop);

    }

	return 0;
}