Thursday, November 14, 2019

[OpenCV Tutorial] $3 - Adding (blending) two images using OpenCV

Goal

In this tutorial you will learn:
  • what is linear blending and why it is useful;
  • how to add two images using cv::addWeighted

Theory

Note
From our previous tutorial, we know already a bit of Pixel operators. An interesting dyadic (two-input) operator is the linear blend operator:
g(x)=(1α)f0(x)+αf1(x)

By varying α from 01 this operator can be used to perform a temporal cross-dissolve between two images or videos, as seen in slide shows and film productions (cool, eh?)


Source Code

Download the source code from here.
#include <iostream>
using namespace cv;
int main( void )
{
double alpha = 0.5; double beta; double input;
Mat src1, src2, dst;
std::cout<<" Simple Linear Blender "<<std::endl;
std::cout<<"-----------------------"<<std::endl;
std::cout<<"* Enter alpha [0-1]: ";
std::cin>>input;
// We use the alpha provided by the user if it is between 0 and 1
if( alpha >= 0 && alpha <= 1 )
{ alpha = input; }
src1 = imread("../data/LinuxLogo.jpg");
src2 = imread("../data/WindowsLogo.jpg");
if( src1.empty() ) { std::cout<< "Error loading src1"<<std::endl; return -1; }
if( src2.empty() ) { std::cout<< "Error loading src2"<<std::endl; return -1; }
beta = ( 1.0 - alpha );
addWeighted( src1, alpha, src2, beta, 0.0, dst);
imshow( "Linear Blend", dst );
waitKey(0);
return 0;
}

Explanation

  1. Since we are going to perform:
    g(x)=(1α)f0(x)+αf1(x)

    We need two source images ( f0(x) and f1(x)). So, we load them in the usual way:
    src1 = imread("../data/LinuxLogo.jpg");
    src2 = imread("../data/WindowsLogo.jpg");
    warning
    Since we are adding src1 and src2, they both have to be of the same size (width and height) and type.
  2. Now we need to generate the g(x) image. For this, the function cv::addWeighted comes quite handy:
    beta = ( 1.0 - alpha );
    addWeighted( src1, alpha, src2, beta, 0.0, dst);
    since cv::addWeighted produces:
    dst=αsrc1+βsrc2+γ

    In this case, gamma is the argument 0.0 in the code above.
  3. Create windows, show the images and wait for the user to end the program.
    imshow( "Linear Blend", dst );
    waitKey(0);


===

Run and set value for alpha from 0 to 1.0

Ex: Alpha = 0, show image 1.
Alpha = 1,show image 2.




No comments:

Post a Comment

Back to Top