user2958571
user2958571

Reputation: 133

Opencv c++ drawing on image

I'm trying to draw a circle on image after a mouse click.

#include <stdio.h>
#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/nonfree/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

using namespace cv;


static Mat img_object;

static void onMouse(int event, int x, int y, int, void*){
    Point pt1 = Point(x, y);
    circle(img_object, pt1, 1, Scalar(0, 255, 0), 100, 8, 0);
    imshow("Display window", img_object);
}

int main(int argc, char** argv)
{
    img_object = imread("pic.jpg");

    setMouseCallback("Display window", onMouse, 0);

    imshow("Display window", img_object);

    waitKey(0);

    return 0;
}

When I run it the image is shown but nothing happens when I click on the image.

Upvotes: 0

Views: 8561

Answers (1)

berak
berak

Reputation: 39796

you're redeclaring a local Mat:

static Mat img_object = imread("pic.jpg");

inside main, thus shadowing the global one.

replace that line with:

img_object = imread("pic.jpg");

and everything will be fine.

----

better even, skip the global object, and pass the mat to the callback function:

using namespace cv;

static void onMouse(int event, int x, int y, int, void* imgptr){
    if ( event != 1 ) return;     // only draw on lmouse down
    Mat & img = (*(Mat*)imgptr)); // first cast, then deref
    Point pt1 = Point(x, y);
    circle(img, pt1, 1, Scalar(0, 255, 0), 100, 8, 0);
    imshow("Display window", img);
    waitKey(1);
}

int main(int argc, char** argv)
{
    namedWindow("Display window",0);
    Mat img = imread("pic.jpg");
    setMouseCallback("Display window", onMouse, &img); // pass ptr to mat here
    imshow("Display window", img);
    waitKey(0);
    return 0;
}

Upvotes: 4

Related Questions