我想知道在opencv中是否可以做这样的事情。我想在每个轨迹栏上调用相同的回调函数onChange,并在内部onChange()提取中以某种方式改变3个滑块之一。

cv::createTrackbar("bar_0", "window", &bSliderValue1, 100, onChange, (void*)&data);
cv::createTrackbar("bar_1", "window", &bSliderValue2, 100, onChange, (void*)&data);
cv::createTrackbar("bar_2", "window", &bSliderValue3, 100, onChange, (void*)&data);

函数onChange是这样的:
static void onChange(int value, void* userdata)
{

}

最佳答案

您可以添加带有跟踪栏ID的用户数据

struct Userdata {
    int sliderId;
    std::string sliderName;
};

const Userdata userdata0 {0, "bar_0"};
cv::createTrackbar("bar_0", "window", &bSliderValue1, 100, onChange, const_cast<Userdata*>(&userdata0));

const Userdata userdata1 {1, "bar_1"};
cv::createTrackbar("bar_1", "window", &bSliderValue2, 100, onChange, const_cast<Userdata*>(&userdata1));

const Userdata userdata2 {2, "bar_2"};
cv::createTrackbar("bar_2", "window", &bSliderValue3, 100, onChange, const_cast<Userdata*>(&userdata2));

static void onChange(int value, void* userdata)
{
    const auto &slider = const_cast<const Userdata&>(*static_cast<Userdata*>(userdata));
    auto sliderId = slider.sliderId;
    auto sliderName = slider.sliderName;
}

您应将C强制转换替换为C++强制转换。

这是没有const的示例。
struct Userdata {
    int sliderId;
    std::string sliderName;
};

Userdata userdata0 {0, "bar_0"};
cv::createTrackbar("bar_0", "window", &bSliderValue1, 100, onChange, &userdata0);

Userdata userdata1 {1, "bar_1"};
cv::createTrackbar("bar_1", "window", &bSliderValue2, 100, onChange, &userdata1);

Userdata userdata2 {2, "bar_2"};
cv::createTrackbar("bar_2", "window", &bSliderValue3, 100, onChange, &userdata2);

static void onChange(int value, void* userdata)
{
    const auto &slider = *static_cast<Userdata*>(userdata);
    auto sliderId = slider.sliderId;
    auto sliderName = slider.sliderName;
}

关于c++ - 使用相同的回调函数OpenCV C++管理多个轨迹栏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61298196/

10-10 21:29