Saturday, June 25, 2016

How to Crop Video from Webcam using OpenCV

Posted by Md. Hanif Ali Sohag on Saturday, June 25, 2016 in | 1 comment
How to Crop Video from Webcam using OpenCV
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:
How to crop video

1 comment:

  1. if you please provide some details it'll be much helpful.
    thanks for the initiative

    ReplyDelete