Ask Your Question
0

Save image using callBack Function

asked 2019-11-28 10:54:08 -0600

updated 2019-11-28 10:54:45 -0600

Hello,

I am trying to create a window with Opencv that display a video stream and above a rectangle (gray rectangle), my goal is to save the image of the current video stream when the user click on the gray rectangle, but I can't figure out how to pass the Mat "img" to the callback function to save it:

image description

image description

 #include <opencv2\opencv.hpp>
 #include <iostream>
 using namespace cv;
 using namespace std;
Mat3b canvas;
string buttonText("Save an  image!");
string winName = "My cool GUI v0.1";    
Rect button;   

void callBackFunc(int event, int x, int y, int flags, void* userdata)
{
    if (event == EVENT_LBUTTONDOWN)
    {
        if (button.contains(Point(x, y)))
        {
            cout << "Clicked!" << endl;
            rectangle(canvas(button), button, Scalar(0, 0, 255), 2);
        }
    }
    if (event == EVENT_LBUTTONUP)
    {
        rectangle(canvas, button, Scalar(200, 200, 200), 2);
    }

    imshow(winName, canvas);
    waitKey(1);
}

int main()
{
    Mat img;
    VideoCapture cap(0); //caméra par défault
    for (;;)
    {
        cap >> img; // get a new frame from camera      
        while (img.empty()) {
            std::cout << "Frame empty" << std::endl;
            continue;
        }
        //cout << "Resolution" << img.size() << endl;        

        // Your button
        button = Rect(0, 0, img.cols, 50);

        // The canvas
        canvas = Mat3b(img.rows + button.height, img.cols, Vec3b(0, 0, 0));

        // Draw the button
        canvas(button) = Vec3b(200, 200, 200);
        putText(canvas(button), buttonText, Point(button.width*0.35, button.height*0.7), FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 0));

        // Draw the image
        img.copyTo(canvas(Rect(0, button.height, img.cols, img.rows)));

        // Setup callback function
        namedWindow(winName);
        setMouseCallback(winName, callBackFunc);

        imshow(winName, canvas);
            waitKey(1);
    }

    return 0;
}

I need your help and thank you

edit retag flag offensive close merge delete

1 answer

Sort by » oldest newest most voted
3

answered 2019-11-28 12:57:21 -0600

mvuori gravatar image

Just define img in the top of the file insted of inside the function.

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2019-11-28 10:54:08 -0600

Seen: 804 times

Last updated: Nov 28 '19