Creating trackbar in c++

Hi Guys,

I am trying to detect colors using opencv. To do that, I convert the image to HSV colorspace first and then do the operation. And to provide the range of hsv min and max, I wanted to use the trackbars but it seems like I can not create trackbars with normal functions.

#include<iostream>
#include<opencv2/imgcodecs.hpp>
#include<opencv2/imgproc.hpp>
#include<opencv2/highgui.hpp>

int hmin = 0, smin = 110, vmin = 153, hmax = 19, smax = 240, vmax = 255;

int main() {
  std::string imagePath = "/Users/apple/Learning/youtubeCourse/Learn-OpenCV-cpp-in-4-Hours-main/Resources/lambo.png";
  cv::Mat imageMat      = cv::imread(imagePath);
  cv::imshow("Original image", imageMat);

  cv::Mat hsvMat;
  cv::cvtColor(imageMat, hsvMat, cv::COLOR_BGR2HSV);
  cv::imshow("HSV image", hsvMat);

  cv::namedWindow("Trackbars", 0); 
  cv::createTrackbar("Hue min", "Trackbars", &hmin, 200, 0); 

  cv::Mat oneColorMatrix;
  while(true) {
    cv::Scalar lower(hmin, smin, vmin);
    cv::Scalar higher(hmax, smax, vmax);
    cv::inRange(hsvMat, lower, higher, oneColorMatrix);
    cv::imshow("One color matrix", oneColorMatrix);
  }

  cv::waitKey(0);
}

And the error message I get during execution is this:

[ WARN:0] global /tmp/opencv-20210728-15491-hx6tk7/opencv-4.5.3/modules/highgui/src/window.cpp (704) createTrackbar UI/Trackbar(Hue min@Trackbars): Using 'value' pointer is unsafe and deprecated. Use NULL as value pointer. To fetch trackbar value setup callback.

Does this ring a bell to anyone?

yea, the api is changing here, they are trying to get away from using “raw pointers” in the interface. so this:

should be changed to:

cv::createTrackbar("Hue min", "Trackbars", nullptr, 200, 0);
cv::setTrackbarPos("Hue min", "Trackbars", hmin);

also:

  while(true) {
    hmin = cv::getTrackbarPos("Hue min", "Trackbars");
 
    cv::Scalar lower(hmin, smin, vmin);
    ...
1 Like

I see. Can you please enlighten me the reason for that as well. Thanks a lot for your reply.

This issue doesn’t occur on the 4.5.2 version. It happened on 4.5.3. The third parameter in createTrackbar values, this should be a pointer to that bar; However, when I use the code above, that value is fixed no matter how you move the bar. This might be a BUG I guess.

 hmin = cv::getTrackbarPos("Hue min", "Trackbars");