Ask Your Question

Revision history [back]

another example

#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>

using namespace std;
using namespace cv;

bool selectObject = false;
Rect selection;
Point origin;
Mat image;

vector<Rect> selections;

static void onMouse(int event, int x, int y, int, void*)
{
    switch (event)
    {
    case EVENT_LBUTTONDOWN:
        origin = Point(x, y);
        selectObject = true;
        break;
    case EVENT_LBUTTONUP:
    {
        selectObject = false;
        selections.push_back(selection);
        break;
    }
    }

    if (selectObject)
    {
        selection.x = MIN(x, origin.x);
        selection.y = MIN(y, origin.y);
        selection.width = std::abs(x - origin.x) + 1;
        selection.height = std::abs(y - origin.y) + 1;
        selection &= Rect(0, 0, image.cols, image.rows);
    }
}

int main(int argc, char** argv)
{
    VideoCapture cap(0);
    namedWindow("Demo");
    setMouseCallback("Demo", onMouse);

    while (true)
    {
        cap >> image;

        for(int i=0; i < selections.size(); i++)
        {
            rectangle(image, selections[i], Scalar(0, 255, 0), 2);
        }

        if (selectObject && selection.width > 0 && selection.height > 0)
        {
            rectangle(image, selection, Scalar(0, 0, 255), 2);
        }
        imshow("Demo", image);
        char key = waitKey(1);

        if (key == 27)
            break;

        if (key == 'c') // clear selections
        {
            selections.clear();
        }
    }


    return 0;
}