如何在OpenCV中使用cv :: createButton原型

我想了解如何使用在OpenCV文档中定义的cv :: createButton:

http://opencv.jp/opencv-2svn_org/cpp/highgui_qt_new_functions.html#cv-createbutton

它说原型是:

createButton(const string& button_name CV_DEFAULT(NULL), ButtonCallback on_change CV_DEFAULT(NULL), void* userdata CV_DEFAULT(NULL), int button_type CV_DEFAULT(CV_PUSH_BUTTON), int initial_button_state CV_DEFAULT(0) 

但我不知道如何定义函数ButtonCallback以捕获按钮事件。

我做:

 cvCreateButton("button6", callbackButton2, pointer, CV_PUSH_BUTTON, 0); 

声明按钮和

 void callbackButton2(int state, void *pointer){ printf("ok"); } 

但它不起作用。

我不知道第三个参数“void * userdata”的含义。

有谁可以帮助我吗?

谢谢。

我们仍然不知道什么对我不起作用 ,但我会提供一些有关如何使用回调userdata的信息。

如签名所示, void* userdata是一个可用于向回调发送/接收数据的参数。 这纯粹是可选的,所以如果你没有任何用处,只需传递NULL

在下面的示例中,我将使用userdata从回调中检索数据。 您可能已经注意到回调从OpenCV接收state信息。 我有兴趣存储这个值并使其可用于main()

为此,我定义了一个自定义数据类型,并在main()上声明了这种类型的变量。 自定义类型有一个int成员来存储我们的回调接收的state和一个互斥锁,我们将用它来保护自定义类型不被2个线程(回调和main() )同时读/写。

 #include  #include  #include  #include  #include  using namespace cv; typedef struct custom_data { int state; pthread_mutex_t mtx; } custom_data_t; void my_button_cb(int state, void* userdata) { std::cout << "@my_button_cb" << std::endl; // convert userdata to the right type custom_data_t* ptr = (custom_data_t*)userdata; if (!ptr) { std::cout << "@my_button_cb userdata is empty" << std::endl; return; } // lock mutex to protect data from being modified by the // main() thread pthread_mutex_lock(&ptr->mtx); ptr->state = state; // unlock mutex pthread_mutex_unlock(&ptr->mtx); } int main() { // declare and initialize our userdata custom_data_t my_data = { 0 }; createButton("dummy_button", my_button_cb, &my_data, CV_PUSH_BUTTON, 0); // For testing purposes, go ahead and click the button to activate // our callback. // waiting for key press  on the console to continue the execution getchar(); // At this point the button exists, and our callback was called // (if you clicked the button). In a real application, the button is // probably going to be pressed again, and again, so we need to protect // our data from being modified while we are accessing it. pthread_mutex_lock(&my_data.mtx); std::cout << "The state retrieved by the callback is: " << my_data.state << std::endl; // unlock mutex pthread_mutex_unlock(&my_data.mtx); return 0; } 

它不起作用的原因是因为cvCreateButton实现有一个错误导致按钮点击被忽略:

https://code.ros.org/trac/opencv/ticket/786

现在这已经固定在行李箱中,因此如果您使用行李箱,则按钮单击现在应该再次正常工作。 它最终应该进入正式版本。