在OpenCV中是否有类似MATLAB的'impixelinfo()'函数?

3
我正在寻找在OpenCV中类似于MATLAB中的impixelinfo()的功能。

impixelinfo()会显示:

  1. 像素点的位置 (x, y)

  2. 鼠标悬停在图像上时像素强度

    例如:

MATLAB中的impixelinfo()如图所示

在OpenCV中是否已经有实现?是否有任何个人版本的创建?

1个回答

7
您可以这样做:
#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);
   }
}

在这里输入图片描述

由于有帮助的评论,我(希望)改进了代码,现在可以处理灰度图像,并将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;
      }
   }
}

1
我应该检查图片是否有3个通道,并稍微不同地处理灰度图像。也许以后再说... - Mark Setchell
看起来不错!谢谢。如果我想查看灰度图像的强度值,我将更改:img.at<Vec3b>(y,x)为img.at<char>(y,x)...但为什么我看到奇怪的字符而不是0-255之间的整数呢? - jok23
你需要将char转换为int,然后一切都会没问题的。 - Mark Setchell
顺便提一下,如果你想匹配 impixelinfo 的行为,当显示它们的值时,你可能需要翻转 B 和 R 通道的顺序。正如你已经知道的那样,像素布局的顺序是相反的。同时转换成灰度也很容易。在事件处理程序中,只需检查图像中通道的数量,并在使用 at 时相应地调整模板分辨率。cv::Mat 有一个 channels() 方法。无论如何,干得好。+1。 - rayryeng
谢谢大家的反馈 - 我已经更新了代码,希望能够反映出你们的意见并进行改进。 - Mark Setchell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接