你可以这样做:
#include
#include
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(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);
}
}
作为有用的评论的结果,我(希望)改进了代码并且现在处理灰度图像,并且还将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(y,x) << endl;
} else {
cout << "RGB Pixel (" << x << ", " << y << "): " << (int)img.at(y,x)[2] << "/" << (int)img.at(y,x)[1] << "/" << (int)img.at(y,x)[0] << endl;
}
}
}