1
Adding (blending) two images using OpenCV {#tutorial_adding_images}
2
=========================================
7
In this tutorial you will learn:
9
- what is *linear blending* and why it is useful;
10
- how to add two images using @ref cv::addWeighted
16
The explanation below belongs to the book [Computer Vision: Algorithms and
17
Applications](http://szeliski.org/Book/) by Richard Szeliski
19
From our previous tutorial, we know already a bit of *Pixel operators*. An interesting dyadic
20
(two-input) operator is the *linear blend operator*:
22
\f[g(x) = (1 - \alpha)f_{0}(x) + \alpha f_{1}(x)\f]
24
By varying \f$\alpha\f$ from \f$0 \rightarrow 1\f$ this operator can be used to perform a temporal
25
*cross-dissolve* between two images or videos, as seen in slide shows and film productions (cool,
31
As usual, after the not-so-lengthy explanation, let's go to the code:
33
#include <opencv2/opencv.hpp>
38
int main( int argc, char** argv )
40
double alpha = 0.5; double beta; double input;
44
/// Ask the user enter alpha
45
std::cout<<" Simple Linear Blender "<<std::endl;
46
std::cout<<"-----------------------"<<std::endl;
47
std::cout<<"* Enter alpha [0-1]: ";
50
/// We use the alpha provided by the user if it is between 0 and 1
51
if( input >= 0.0 && input <= 1.0 )
54
/// Read image ( same size, same type )
55
src1 = imread("../../images/LinuxLogo.jpg");
56
src2 = imread("../../images/WindowsLogo.jpg");
58
if( !src1.data ) { printf("Error loading src1 \n"); return -1; }
59
if( !src2.data ) { printf("Error loading src2 \n"); return -1; }
62
namedWindow("Linear Blend", 1);
64
beta = ( 1.0 - alpha );
65
addWeighted( src1, alpha, src2, beta, 0.0, dst);
67
imshow( "Linear Blend", dst );
76
-# Since we are going to perform:
78
\f[g(x) = (1 - \alpha)f_{0}(x) + \alpha f_{1}(x)\f]
80
We need two source images (\f$f_{0}(x)\f$ and \f$f_{1}(x)\f$). So, we load them in the usual way:
82
src1 = imread("../../images/LinuxLogo.jpg");
83
src2 = imread("../../images/WindowsLogo.jpg");
87
Since we are *adding* *src1* and *src2*, they both have to be of the same size (width and
90
-# Now we need to generate the `g(x)` image. For this, the function add_weighted:addWeighted comes quite handy:
92
beta = ( 1.0 - alpha );
93
addWeighted( src1, alpha, src2, beta, 0.0, dst);
95
since @ref cv::addWeighted produces:
96
\f[dst = \alpha \cdot src1 + \beta \cdot src2 + \gamma\f]
97
In this case, `gamma` is the argument \f$0.0\f$ in the code above.
99
-# Create windows, show the images and wait for the user to end the program.
104
![](images/Adding_Images_Tutorial_Result_Big.jpg)