使用我之前关于这个主题的帖子作为参考:
我能够组装一个快速的 C++/Qt/OpenCV 演示,它创建一个 OpenCV 窗口,并在每次按下鼠标左键时在控制台上写入一条消息。
我相信代码是不言自明的:
主.cpp:
#include <cv.h>
#include <highgui.h>
#include <iostream>
#include <QtWidgets/QApplication>
void on_mouse(int event, int x, int y, int flags, void* param)
{
if (event == CV_EVENT_LBUTTONDOWN)
{
std::cout << "@ Left mouse button pressed at: " << x << "," << y << std::endl;
}
}
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
IplImage* img = cvLoadImage("/Users/karlphillip/workspace/opencv/qt_mouse/LeafGlyph.jpg");
if (!img)
{
std::cout << "!!! Failed to load image" << std::endl;
return -1;
}
cvNamedWindow("result", CV_WINDOW_AUTOSIZE);
cvSetMouseCallback("result",&on_mouse, 0);
cvShowImage("result", img);
cvWaitKey(0);
return app.exec();
}
project.pro(在 Mac OS X 上使用):
TEMPLATE = app
QT += widgets
## OpenCV settings for Mac OS X
macx {
INCLUDEPATH += /usr/local/include/opencv
LIBS += -L/usr/local/lib/ \
-lopencv_core \
-lopencv_highgui \
-lopencv_imgproc
}
SOURCES += \
main.cpp
关于您的实施的注意事项:
我建议您将呼叫转移cvSetMouseCallback()
到您呼叫的任何地方cvNamedWindow()
。我怀疑这样做的正确位置是在MainWindow
应该创建窗口的构造函数中,对吧?!然后,您还必须将其定义on_mouse()
为静态成员MainWindow
并实现它。
如果您这样做,您的代码将类似于:
void MainWindow::on_mouse(int event, int x, int y, int flags, void* param)
{
if (event == CV_EVENT_LBUTTONDOWN)
{
std::cout << "@ Left mouse button pressed at: " << x << "," << y << std::endl;
}
}
MainWindow::MainWindow()
{
IplImage* img = cvLoadImage("/Users/karlphillip/workspace/opencv/qt_mouse/LeafGlyph.jpg");
if (!img)
{
std::cout << "!!! Failed to load image" << std::endl;
return;
}
cvNamedWindow("result", CV_WINDOW_AUTOSIZE);
cvSetMouseCallback("result",&on_mouse, 0);
cvShowImage("result", img);
cvWaitKey(0);
}