2013-02-17 59 views
5

這是我試過的代碼,只有座標值被打印,但不是像素值。使用鼠標回調打印座標和像素值

#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"; 

} 

我得到了輸出爲: -

screenshot

的座標值被印刷但是像素值沒有被正確打印。我犯的錯誤是什麼?

回答

5

cout將uchar打印爲字符,就像您看到的那樣。

只是包裝他們鑄造爲int的印刷:

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

also note, that it's at<uchar>(y,x), not x,y 
+0

謝謝@berak。另一個qn:在.at (y,x)中,哪一個表示行號和列號? (row_no,column_no)' – 2013-02-17 10:39:25

+0

'基本上:y = row_no,x = column_no' – berak 2013-02-17 11:43:38