2017-02-17 182 views

回答

6

你可以做這樣的事情:

#include <opencv2/opencv.hpp> 
#include <iostream> 

using namespace std; 
using namespace cv; 

Mat img; 

void 
CallBackFunc(int event,int x,int y,int flags,void* userdata) 
{ 
    if(event==EVENT_MOUSEMOVE){ 
     cout << "Pixel (" << x << ", " << y << "): " << img.at<Vec3b>(y,x) << endl; 
    } 
} 

int main() 
{ 
    // Read image from file 
    img=imread("demo.jpg"); 

    // Check it loaded 
    if(img.empty()) 
    { 
     cout << "Error loading the image" << endl; 
     exit(1); 
    } 

    //Create a window 
    namedWindow("ImageDisplay",1); 

    // Register a mouse callback 
    setMouseCallback("ImageDisplay",CallBackFunc,nullptr); 

    // Main loop 
    while(true){ 
     imshow("ImageDisplay",img); 
     waitKey(50); 
    } 
} 

enter image description here

作爲的有益意見的結果,我(希望)提高了代碼,現在處理灰度圖像,並且還設置RGB排序更類似於非OpenCV愛好者可能期望的 - 即RGB而不是BGR。更新後的函數如下所示:

void 
CallBackFunc(int event,int x,int y,int flags,void* userdata) 
{ 
    if(event==EVENT_MOUSEMOVE){ 
     // Test if greyscale or color 
     if(img.channels()==1){ 
     cout << "Grey Pixel (" << x << ", " << y << "): " << (int)img.at<uchar>(y,x) << endl; 
     } else { 
     cout << "RGB Pixel (" << x << ", " << y << "): " << (int)img.at<Vec3b>(y,x)[2] << "/" << (int)img.at<Vec3b>(y,x)[1] << "/" << (int)img.at<Vec3b>(y,x)[0] << endl; 
     } 
    } 
} 
+0

這是超爽! –

+1

我可能應該檢查圖像有3個通道,並略微不同地處理灰度圖像。也許以後... –

+0

這看起來不錯! TNX。如果我想看到從灰度圖像的亮度值更改:img.at (Y,X),以img.at (Y,X)......但爲什麼然後我看到奇怪的字符,而不是從0-255的整數?? – jok23

相關問題