Ask Your Question

Revision history [back]

take a look at this code

#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, canvas;
String win_name = "Cropping Demo";
vector<Rect> selections;

static bool showSelections()
{
    for (size_t i = 0; i< selections.size(); i++)
    {
        rectangle(canvas, selections[i], Scalar(0, 255, 0), 2);
    }
    imshow(win_name, canvas);
    return true;
}

static void onMouse(int event, int x, int y, int, void*)
{
    switch (event)
    {
    case CV_EVENT_LBUTTONDOWN:
        origin = Point(x, y);
        selectObject = true;
        break;
    case CV_EVENT_LBUTTONUP:
    {
        selectObject = false;
        selections.push_back(selection);
        showSelections();
        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);

        if (selection.width > 0 && selection.height > 0)
        {
            Mat canvascopy;
            canvas.copyTo(canvascopy);
            Mat roi = canvascopy(selection);
            bitwise_not(roi, roi);
            imshow(win_name, canvascopy);
        }
    }
}


int main(int argc, const char** argv)
{
    String file_name = argv[1];
    image = imread(file_name);
    image.copyTo(canvas);

    namedWindow(win_name);
    setMouseCallback(win_name, onMouse);

    imshow(win_name, image);

    while (true)
    {
        int key = waitKey(0);

        if (key == 27)
            break;

        if (key == 's') // crops and saves selections
        {
            for (size_t i = 0; i < selections.size(); i++)
            {
                String save_file_name = file_name + format("%02d.jpg", i);
                imwrite(save_file_name, image(selections[i]));
            }
        }

        if ( (key == 'd') & (selections.size() > 0) ) // delete last selection
        {
            selections.erase(selections.end() -1 );
            image.copyTo(canvas);
            showSelections();
        }
    }
    return 0;
}