目录
1、介绍
实现获取鼠标点击处的图像的坐标和像素值,灰度图显示其灰度值,RGB图显示rgb的值。
OpenCV获取灰度值及彩色像素值的方法:
//灰度图像:
image.at<uchar>(j, i) //j为行数,i为列数
//BGR彩色图像
image.at<Vec3b>(j, i)[0] //B分量
image.at<Vec3b>(j, i)[1] //G分量
image.at<Vec3b>(j, i)[2] //R分量
这里要通过鼠标点击事件来获取鼠标点击的位置和状态,选择OpenCV的setMouseCallback回调函数实现。
2、效果展示
3、代码实现
onMouse.h
#ifndef ONMOUSE_H
#define ONMOUSE_H
#include<iostream>
#include<opencv2/opencv.hpp>
using namespace cv;
using namespace std;
void onMouse(int event, int x, int y, int flags, void* param); //evnet:鼠标事件类型 x,y:鼠标坐标 flags:鼠标哪个键
void onMouse(int event, int x, int y, int flags, void* param) //evnet:鼠标事件类型 x,y:鼠标坐标 flags:鼠标哪个键
{
Mat* im = reinterpret_cast<Mat*>(param);
switch (event) {
case EVENT_LBUTTONDOWN:
//显示图像像素值
if (static_cast<int>(im->channels()) == 1)
{
//若图像为单通道图像,则显示鼠标点击的坐标以及灰度值
switch (im->type())
{
case 0:
cout << "at (" << x << ", " << y << " ) value is: " << static_cast<int>(im->at<uchar>(Point(x, y))) << endl; break;
case 1:
cout << "at (" << x << ", " << y << " ) value is: " << static_cast<int>(im->at<char>(Point(x, y))) << endl; break;
case 2:
cout << "at (" << x << ", " << y << " ) value is: " << static_cast<int>(im->at<ushort>(Point(x, y))) << endl; break;
case 3:
cout << "at (" << x << ", " << y << " ) value is: " << static_cast<int>(im->at<short>(Point(x, y))) << endl; break;
case 4:
cout << "at (" << x << ", " << y << " ) value is: " << static_cast<int>(im->at<int>(Point(x, y))) << endl; break;
case 5:
cout << "at (" << x << ", " << y << " ) value is: " << static_cast<int>(im->at<float>(Point(x, y))) << endl; break;
case 6:
cout << "at (" << x << ", " << y << " ) value is: " << static_cast<int>(im->at<double>(Point(x, y))) << endl; break;
}
}
else
{
//若图像为彩色图像,则显示鼠标点击坐标以及对应的B, G, R值
cout << "at (" << x << ", " << y << ")"
<< " B value is: " << static_cast<int>(im->at<Vec3b>(Point(x, y))[0])
<< " G value is: " << static_cast<int>(im->at<Vec3b>(Point(x, y))[1])
<< " R value is: " << static_cast<int>(im->at<Vec3b>(Point(x, y))[2])
<< endl;
}
break;
}
}
#endif // ONMOUSE_H
头文件onMouse.h主要实现鼠标点击事件的回调,输出点击时鼠标的坐标和对应的像素值。
main.cpp
Mat image1 = imread("lena.png");
if(image1.empty()){
qDebug()<<"读取图像错误";
}
imshow("image1",image1);
setMouseCallback("image1", onMouse, reinterpret_cast<void*>(&image1));
这里我用的Qt来实现的,要在pro文件里添加OpenCV库的引用
win32:CONFIG(release, debug|release): LIBS += -LD:/opencv/build/x64/vc15/lib/ -lopencv_world455
else:win32:CONFIG(debug, debug|release): LIBS += -LD:/opencv/build/x64/vc15/lib/ -lopencv_world455d
else:unix: LIBS += -LD:/opencv/build/x64/vc15/lib/ -lopencv_world455
INCLUDEPATH += D:/opencv/build/include
DEPENDPATH += D:/opencv/build/include
4、源码展示
本小例程的代码放到我的开源gitte项目里,欢迎一起学习,也希望能收获你的小星星。
项目源码PixelPos_Mouse