Shweta Chandel
Shweta Chandel

Reputation: 895

Detect touch on OpenCV C++ window

I'm trying to open web-cam video and then pause it on first tap and then close it on second tap on a touchscreen display. I'm using OpenCV version 3.4.0.

Currently I can do it by either pressing q key or by closing window but I am unable to do it with screen tap. Here is my code sample:

bool exit_flag = false;
do
{
    cv::imshow("window", draw_frame);
    int key = cv::waitKey(3);
    if (key == 'q'|| cv::getWindowProperty("window", cv::WND_PROP_ASPECT_RATIO) < 0) 
    { 
        //do_something
        exit_flag = true;
    }
} while (!exit_flag);

cv::waitKey(0);
cv::destroyWindow("window"); 

I tried using cv::EVENT_LBUTTONDOWN but couldn't use it properly to bring any positive results.

Pardon me if code isn't proper, I have created a sample for demonstration and I'm not very good at C++.

Upvotes: 1

Views: 1146

Answers (1)

Yunus Temurlenk
Yunus Temurlenk

Reputation: 4367

If you want to close your imshow window using mouse, you can simply use setMouseCallback. Here is my approach: you can close your window by "q" keyword or by simply clicking to window:

#include "opencv2/highgui/highgui.hpp"
#include <iostream>

using namespace std;
using namespace cv;

static bool exit_flag = false;


static void mouseHandler(int event,int x,int y, int flags,void* param){
    if(event==1)
    exit_flag = true;
}


int main(int argc, char **argv) {

    Mat draw_frame = imread("/ur/image/directory/photo.jpg");
    do {
    cv::imshow("window", draw_frame);
    int key = cv::waitKey(3);

    setMouseCallback("window",mouseHandler);

    if (key == 'q'|| cv::getWindowProperty("window", cv::WND_PROP_ASPECT_RATIO) < 0)
        {
        //do_something

        exit_flag = true;
        }
    } while (!exit_flag);

    cv::destroyWindow("window");
}

Upvotes: 1

Related Questions