iFreilicht
iFreilicht

Reputation: 14484

Can I get the mouse position in OpenCV without a mouse event?

All the tutorials I find use setMouseCallback() to set a callback function to which the mouse position is passed. Unfortunately, this function is only called when an actual mouse event is occurring, but I'd like to get the mouse position while no keys on my mouse are pressed.

Is that possible in OpenCV?

Upvotes: 9

Views: 10145

Answers (1)

Miki
Miki

Reputation: 41765

You can use EVENT_MOUSEMOVE to get the position of the mouse:

#include <opencv2\opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;

void mouse_callback(int  event, int  x, int  y, int  flag, void *param)
{
    if (event == EVENT_MOUSEMOVE) {
        cout << "(" << x << ", " << y << ")" << endl;
    }
}

int main()
{
    cv::Mat3b img(200, 200, Vec3b(0, 255, 0));

    namedWindow("example");
    setMouseCallback("example", mouse_callback);

    imshow("example", img);
    waitKey();

    return 0;
}

Upvotes: 8

Related Questions