OpenCV  4.2.0
Open Source Computer Vision
Adding (blending) two images using OpenCV

Prev Tutorial: Operations with images
Next Tutorial: Changing the contrast and brightness of an image!

Goal

In this tutorial you will learn:

  • what is linear blending and why it is useful;
  • how to add two images using addWeighted()

Theory

Note
The explanation below belongs to the book Computer Vision: Algorithms and Applications by Richard Szeliski

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 - \alpha)f_{0}(x) + \alpha f_{1}(x)\]

By varying \(\alpha\) from \(0 \rightarrow 1\) 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

Explanation

Since we are going to perform:

\[g(x) = (1 - \alpha)f_{0}(x) + \alpha f_{1}(x)\]

We need two source images ( \(f_{0}(x)\) and \(f_{1}(x)\)). So, we load them in the usual way:

We used the following images: LinuxLogo.jpg and WindowsLogo.jpg

Warning
Since we are adding src1 and src2, they both have to be of the same size (width and height) and type.

Now we need to generate the g(x) image. For this, the function addWeighted() comes quite handy:

since addWeighted() produces:

\[dst = \alpha \cdot src1 + \beta \cdot src2 + \gamma\]

In this case, gamma is the argument \(0.0\) in the code above.

Create windows, show the images and wait for the user to end the program.

Result

cv::String
std::string String
Definition: cvstd.hpp:150
cv::samples::findFile
cv::String findFile(const cv::String &relative_path, bool required=true, bool silentMode=false)
Try to find requested data file.
cv::waitKey
int waitKey(int delay=0)
Waits for a pressed key.
highgui.hpp
cv::addWeighted
void addWeighted(InputArray src1, double alpha, InputArray src2, double beta, double gamma, OutputArray dst, int dtype=-1)
Calculates the weighted sum of two arrays.
cv::imread
Mat imread(const String &filename, int flags=IMREAD_COLOR)
Loads an image from a file.
cv::Mat::empty
bool empty() const
Returns true if the array has no elements.
imgcodecs.hpp
cv::dnn::print
static void print(const MatShape &shape, const String &name="")
Definition: shape_utils.hpp:188
cv::imshow
void imshow(const String &winname, InputArray mat)
Displays an image in the specified window.
cv::Mat
n-dimensional dense array class
Definition: mat.hpp:792
cv::imshow
void imshow(const String &winname, const ogl::Texture2D &tex)
Displays OpenGL 2D texture in the specified window.
cv
"black box" representation of the file storage associated with a file on disk.
Definition: affine.hpp:52
cv::destroyAllWindows
void destroyAllWindows()
Destroys all of the HighGUI windows.
cv::detail::strip
gapi::GNetParam strip(T &&t)
Definition: infer.hpp:215