Loading web-font TeX/Math/Italic
OpenCV  
Open Source Computer Vision
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
Adding a Trackbar to our applications!

Next Tutorial: Reading Geospatial Raster files with GDAL

Original author Ana Huamán
Compatibility OpenCV >= 3.0

Goals

In this tutorial you will learn how to:

Code

Let's modify the program made in the tutorial Adding (blending) two images using OpenCV. We will let the user enter the \alpha value by using the Trackbar.

This tutorial code's is shown lines below. You can also download it from here

#include <iostream>
using namespace cv;
using std::cout;
const int alpha_slider_max = 100;
int alpha_slider;
double alpha;
double beta;
Mat src1;
Mat src2;
Mat dst;
static void on_trackbar( int, void* )
{
alpha = (double) alpha_slider/alpha_slider_max ;
beta = ( 1.0 - alpha );
addWeighted( src1, alpha, src2, beta, 0.0, dst);
imshow( "Linear Blend", dst );
}
int main( void )
{
src1 = imread( samples::findFile("LinuxLogo.jpg") );
src2 = imread( samples::findFile("WindowsLogo.jpg") );
if( src1.empty() ) { cout << "Error loading src1 \n"; return -1; }
if( src2.empty() ) { cout << "Error loading src2 \n"; return -1; }
alpha_slider = 0;
namedWindow("Linear Blend", WINDOW_AUTOSIZE); // Create Window
char TrackbarName[50];
sprintf( TrackbarName, "Alpha x %d", alpha_slider_max );
createTrackbar( TrackbarName, "Linear Blend", &alpha_slider, alpha_slider_max, on_trackbar );
on_trackbar( alpha_slider, 0 );
waitKey(0);
return 0;
}

Explanation

We only analyze the code that is related to Trackbar:

src1 = imread( samples::findFile("LinuxLogo.jpg") );
src2 = imread( samples::findFile("WindowsLogo.jpg") );
namedWindow("Linear Blend", WINDOW_AUTOSIZE); // Create Window
char TrackbarName[50];
sprintf( TrackbarName, "Alpha x %d", alpha_slider_max );
createTrackbar( TrackbarName, "Linear Blend", &alpha_slider, alpha_slider_max, on_trackbar );

Note the following (C++ code):

Finally, we have to define the callback function on_trackbar for C++ and Python code, using an anonymous inner class listener in Java

static void on_trackbar( int, void* )
{
alpha = (double) alpha_slider/alpha_slider_max ;
beta = ( 1.0 - alpha );
addWeighted( src1, alpha, src2, beta, 0.0, dst);
imshow( "Linear Blend", dst );
}

Note that (C++ code):

Result