Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print coordinates and pixel values using Mouse callback

This is the code which i tried, only the coordinate values are printed but not the pixel values.

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

void onMouse( int event, int x, int y, int, void* );
using namespace cv;

Mat img = cv::imread("b.jpg", 0); // force grayscale
Mat thresh=Mat::zeros(img.size(),CV_8UC1);

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

    if(!img.data) {
        std::cout << "File not found" << std::endl;
        return -1;
    }

   threshold(img,binary,50,255,THRESH_TOZERO);  

   namedWindow("thresh");
   setMouseCallback( "thresh", onMouse, 0 );

   imshow("thresh",thresh);
}

void onMouse( int event, int x, int y, int, void* )
{
    if( event != CV_EVENT_LBUTTONDOWN )
            return;

    Point pt = Point(x,y);
    std::cout<<"x="<<pt.x<<"\t y="<<pt.y<<"\t value="<<thresh.at<uchar>(x,y)<<"\n";

}

I got the output as :-

screenshot

The coordinate values are printed but the pixel values are not printed properly. What is the mistake i committed??

like image 915
Karthik Murugan Avatar asked Feb 17 '13 09:02

Karthik Murugan


People also ask

How does OpenCV Check mouse clicks?

All you have do is to define a callback function in the OpenCV C++ code attaching to the OpenCV window. That callback function will be called every time, mouse events occur. That callback function will also give the coordinates of the mouse events. (e.g - (x, y) coordinate of a mouse click).


1 Answers

cout prints uchar's as characters, like the ones you see.

just wrap them with a cast to int for the printing:

cout << int( thresh.at<uchar>(y,x) )

also note, that it's at<uchar>(y,x), not x,y
like image 73
berak Avatar answered Oct 06 '22 03:10

berak