Life2Coding
How to Crop Video from Webcam using OpenCV

How to Crop Video from Webcam using OpenCV

There will undoubtedly be times when you need to crop your video to delete unnecessary information and draw your viewers’ attention to the most important elements. Your video will look much better if you crop vertical black bars from the sides or remove unwanted areas that don’t contribute anything to the finished product. You may also want to crop video to square or otherwise change the aspect ratio.

In this tutorial you will learn how to crop a video which is captured from webcam.

Code:

#include<opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;

Point point1, point2;
int drag = 0;
cv::Rect rect;
cv:: Mat img,roiImg;
int select_flag = 0;

void mouseHandler(int event, int x, int y, int flags, void* param)
{
	if (event == CV_EVENT_LBUTTONDOWN && !drag)
	{
		/* left button clicked. ROI selection begins */
		select_flag=0;
		point1 = Point(x, y);
		drag = 1;
	}

	if (event == CV_EVENT_MOUSEMOVE && drag)
	{
		/* mouse dragged. ROI being selected */
		Mat img1 = img.clone();
		point2 = Point(x, y);
		rectangle(img1, point1, point2, CV_RGB(255, 0, 0), 3, 8, 0);
		imshow("image", img1);
	}

	if (event == CV_EVENT_LBUTTONUP && drag)
	{
		point2 = Point(x, y);
		rect = Rect(point1.x,point1.y,x-point1.x,y-point1.y);
		drag = 0;
		roiImg = img(rect);
	}

	if (event == CV_EVENT_LBUTTONUP)
	{
		/* ROI selected */
		select_flag = 1;
		drag = 0;
	}
}

int main()
{

	VideoCapture cap = VideoCapture(0); /* Start webcam */
	cap >> img;
	imshow("image", img);
	while(1)
	{
		cap >> img;
		cvSetMouseCallback("image", mouseHandler, NULL);
		if (select_flag == 1)
		{
			imshow("ROI", roiImg); /* show the image bounded by the box */
		}
		rectangle(img, rect, CV_RGB(255, 0, 0), 3, 8, 0);
		imshow("image", img);

		if (waitKey(1) == 27)
		{
			break;
		}
	}
	return 0;
}

Output:

video-473x250 How to Crop Video from Webcam using OpenCV
How to crop video
life2coding_icon [] How to Crop Video from Webcam using OpenCV

One thought on “How to Crop Video from Webcam using OpenCV

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.