Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <opencv2/opencv.hpp>
- #include <iostream>
- // ============================================================================
- struct mouse_state
- {
- mouse_state()
- : position(-1, -1)
- , left_button_held(false)
- , left_button_clicked(false)
- {}
- void new_iteration()
- {
- left_button_clicked = false;
- }
- cv::Point2i position; // Last position where the LMB was down
- bool left_button_held; // Is the LMB down right now?
- bool left_button_clicked; // Was the LMB down in the last iteration?
- };
- // ============================================================================
- void mouse_callback(int event, int x, int y, int flag, void* param)
- {
- mouse_state* state(static_cast<mouse_state*>(param));
- if (event == cv::EVENT_LBUTTONDOWN) {
- std::cout << "LMB down @ (" << x << "," << y << ")\n";
- state->position = cv::Point2i(x, y);
- state->left_button_held = true;
- } else if (event == cv::EVENT_LBUTTONUP) {
- std::cout << "LMB up @(" << x << "," << y << ")\n";
- state->position = cv::Point2i(x, y);
- state->left_button_held = false;
- state->left_button_clicked = true;
- } else if ((flag == cv::EVENT_FLAG_LBUTTON) && (event == cv::EVENT_MOUSEMOVE)) {
- std::cout << "LMB held, mouse moved to (" << x << "," << y << ")\n";
- state->position = cv::Point2i(x, y);
- }
- }
- // ----------------------------------------------------------------------------
- int main(int argc, char** argv)
- {
- cv::String const WINDOW_NAME("Original Feed");
- cv::namedWindow(WINDOW_NAME, CV_WINDOW_AUTOSIZE);
- mouse_state ms;
- cv::setMouseCallback(WINDOW_NAME, mouse_callback, &ms);
- int const FRAME_WIDTH(720);
- int const FRAME_HEIGHT(540);
- cv::VideoCapture cap(0);
- if (!cap.isOpened()) {
- std::cerr << "Unable to open camera, exiting...\n";
- return -1;
- }
- cap.set(CV_CAP_PROP_FRAME_WIDTH, FRAME_WIDTH);
- cap.set(CV_CAP_PROP_FRAME_HEIGHT, FRAME_HEIGHT);
- for (;;) {
- // We can have `image` here, since `cap.read` always gives us
- // a reference to its internal buffer
- cv::Mat image;
- if (!cap.read(image)) {
- std::cerr << "Failed to read image, exiting...\n";
- break; // Failed to read image, nothing else to do
- }
- if (ms.left_button_clicked || ms.left_button_held) {
- cv::circle(image, ms.position, 3, cv::Scalar(0, 0, 255));
- cv::circle(image, ms.position, 10, cv::Scalar(0, 0, 255), 2);
- }
- ms.new_iteration();
- cv::imshow(WINDOW_NAME, image);
- if (cv::waitKey(30) == 27) {
- std::cout << "Esc pressed, exiting...\n";
- break;
- }
- }
- return 0;
- }
- // ============================================================================
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement