c++ vision—use the track bar to set the contrast and brightness of the picture

Track bar: cv::createTrackbar

cv::createTrackbar is a function in the OpenCV library that creates a slider control in a graphical user interface (GUI) that allows the user to adjust the value of a specific parameter while the application is running. This function is called as follows:

int cv::createTrackbar(const std::string & amp; trackbarName, const std::string & amp; windowName, int* value, int count, cv::TrackbarCallback onChange = 0, void* userdata = 0) ;

Parameter explanation:

  • trackbarName: The name of the slider bar, displayed on the label next to the slider bar.
  • windowName: The name of the window containing the slider.
  • value: An integer pointer used to store the current value of the slider. This value is updated when the user moves the slider.
  • count: The maximum value of the slider (the minimum value defaults to 0). This determines the value range of the slider.
  • onChange: An optional callback function that will be called when the user moves the slider. It allows you to perform custom actions when the slider value changes.
  • userdata: An optional user data pointer passed to the callback function, allowing you to use custom data in the callback function.

By creating sliders, users can interactively adjust the values of parameters at runtime, which is useful for image processing and computer vision applications, allowing users to observe the effects and make fine adjustments in real time.

Use the track bar to set contrast

#include <opencv2/opencv.hpp>

//Callback function, used to handle changes in track bar values
void onTrackbar(int value, void* userdata) {<!-- -->
cv::Mat* imagePtr = static_cast<cv::Mat*>(userdata);

//Set contrast enhancement parameters
double alpha = static_cast<double>(value) / 100.0;

//Enhance image contrast
cv::Mat enhancedImage = (*imagePtr) * alpha;

// Display the enhanced image
cv::imshow("Enhanced Image", enhancedImage);
}

int main() {<!-- -->
//Read input image
cv::Mat inputImage = cv::imread("1.jpg");

// Check if the image loaded successfully
if (inputImage.empty()) {<!-- -->
std::cout << "Unable to load input image" << std::endl;
return -1;
}

//Create window
cv::namedWindow("Enhanced Image");

//Create track bar
int initialContrast = 100; // Initial contrast value
cv::createTrackbar("Contrast", "Enhanced Image", & amp;initialContrast, 300, onTrackbar, & amp;inputImage);

//Display initial image
cv::imshow("Enhanced Image", inputImage);

//Wait for key event
cv::waitKey(0);

return 0;
}

Use: image.at(y,x)[c] syntax to set contrast and brightness

image.at(y, x)[c] is a common way to access image pixel values in OpenCV. Let me explain the various parts of this expression:

  • image: This is an OpenCV cv::Mat object, representing an image. cv::Mat is a data structure used in OpenCV to represent images and matrices.

  • at(y, x): This is a way to access the pixel values of an image using the at method. The at method accepts the row and column index in the image as parameters and returns the pixel value at that location.

  • : This is a template parameter that specifies the data type of each pixel in the image. In this case, Vec3b means that each pixel is a 3-channel color pixel, where each channel is an 8-bit unsigned integer.

  • (y, x): These are the row and column coordinates of the pixel to be accessed. y represents the row number, and x represents the column number.

  • [c]: This is the channel index, indicating the channel to be accessed. In a 3-channel color image, there are usually three channels, corresponding to red, green, and blue. [c] allows you to select which channel to access, where c is typically 0 (red channel), 1 (green channel), or 2 (blue channel) ).

Therefore, image.at(y, x)[c] allows you to access the image at (x, y) by specifying channel c pixel value on. This is useful for image processing and pixel-level operations.

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

using namespace std;
using namespace cv;
#include <iostream>
#include <fstream>
using namespace cv; //Contains the cv namespace
#include <opencv2/core/core.hpp>




// Description: Global function declaration
//
static void on_ContrastAndBright(int, void*);
static void ShowHelpText();
//- -------[Global variable declaration part]---------------------------------
// Description: Global variable declaration
//,
int g_nContrastValue; //Contrast value
int g_nBrightValue; //brightness value
Mat g_srcImage, g_dstImage;
// [main() function]--------------------------
// Description: The entry function of the console application, our program starts here
//
int main()
{<!-- -->
//【1】Read the input image
g_srcImage = imread("1.jpg");
if (!g_srcImage.data) {<!-- --> printf("Error reading image, please make sure there is an image specified by imread function in the directory~!"); return false; }
g_dstImage = Mat::zeros(g_srcImage.size(), g_srcImage.type());
//【2】Set the initial values of contrast and brightness
g_nContrastValue = 80;
g_nBrightValue = 80;
//【3】Create rendering window
namedWindow("[Rendering Window]", 1);
//【4】Create track bar
createTrackbar("Contrast: ", "[Rendering Window]", & amp;g_nContrastValue, 300, on_ContrastAndBright);
createTrackbar("Brightness: ", "[Rendering Window]", & amp;g_nBrightValue, 200, on_ContrastAndBright);
//【5】Initialize the callback function
on_ContrastAndBright(g_nContrastValue, 0);
on_ContrastAndBright(g_nBrightValue, 0);
//【6】When the "q" key is pressed, the program exits
while (char(waitKey(1)) != 'q') {<!-- -->}
return 0;
}

//-------------------[on_ContrastAndBright() function]-
// Description: Callback function to change image contrast and brightness values
//----------------
static void on_ContrastAndBright(int, void*)
{<!-- -->
//Create window
namedWindow("[Original Picture Window]", 1);
//Three for loops, perform the operation g_dstImage(i,j) = a*g_srcImage(i,j) + b
for( int y = 0; y< g_srcImage. rows; y + + )
{<!-- -->
for (int x = 0; x < g_srcImage.cols; x + + )
{<!-- -->
for (int c = 0; c < 3; c + + )
{<!-- -->
g_dstImage.at<Vec3b>(y, x)[c] =
saturate_cast<uchar>((g_nContrastValue * 0.01) * (g_srcImage.at<Vec3b>(y, x)[c]) + g_nBrightValue);
}
}
}
//display image
imshow("[Original Image Window]", g_srcImage);
imshow("[Rendering Window]", g_dstImage);
}

Calling the local camera to set the contrast

#include <opencv2/opencv.hpp>

//Global variables are used to store contrast values
int contrast = 100;

//Callback function, used to handle changes in track bar values
void onTrackbar(int value, void* userdata) {<!-- -->
// Store the track bar value in a global variable
contrast = value;
}

int main() {<!-- -->
// Open the default camera (usually the first camera)
cv::VideoCapture cap(0);

// Check if the camera is opened successfully
if (!cap.isOpened()) {<!-- -->
std::cout << "Unable to open camera" << std::endl;
return -1;
}

//Create window
cv::namedWindow("Camera Feed");

//Create track bar
cv::createTrackbar("Contrast", "Camera Feed", & amp;contrast, 200, onTrackbar);

while (true) {<!-- -->
cv::Mat frame;
cap >> frame; // Get frame from camera

//Enhance image contrast
cv::Mat enhancedFrame = frame * (contrast / 100.0);

// Display the enhanced image
cv::imshow("Camera Feed", enhancedFrame);

// Check whether the ESC key is pressed, if so, exit the loop
if (cv::waitKey(1) == 27) {<!-- -->
break;
}
}

// Close camera
cap.release();

// Destroy window
cv::destroyAllWindows();

return 0;
}