opencv 混合两个图像

94 阅读2分钟

本文讲解如何混合两个图像!

1. 目标

在本文中,将学习:

  • 什么是线性混合以及它为什么有用;
  • 如何使用addWeighted() 加和两个图像

2. 理论

从之前的文章中,已经了解了一些像素运算算子。一个有趣的二元(双输入)算子是线性混合算子

g(x)=(1α)f0(x)+αf1(x)g(x)=(1-\alpha )f_{0}(x)+\alpha f_{1}(x)

通过改变α\alpha 010→1此操作符可用于在两个图像或视频之间执行混合相融,像幻灯片和电影制作中的一样(很酷,是吗?)

3. 源代码

从这里下载源代码。

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
using namespace cv;
// we're NOT "using namespace std;" here, to avoid collisions between the beta variable and std::beta in c++17
using std::cin;
using std::cout;
using std::endl;
int main( void )
{
   double alpha = 0.5; double beta; double input;
   Mat src1, src2, dst;
   cout << " Simple Linear Blender " << endl;
   cout << "-----------------------" << endl;
   cout << "* Enter alpha [0.0-1.0]: ";
   cin >> input;
   // We use the alpha provided by the user if it is between 0 and 1
   if( input >= 0 && input <= 1 )
         { alpha = input; }
   
   src1 = imread( samples::findFile("LinuxLogo.jpg") );
   src2 = imread( samples::findFile("WindowsLogo.jpg") );
   if( src1.empty() ) { cout << "Error loading src1" << endl; return EXIT_FAILURE; }
   if( src2.empty() ) { cout << "Error loading src2" << endl; return EXIT_FAILURE; }
   beta = ( 1.0 - alpha );
   addWeighted( src1, alpha, src2, beta, 0.0, dst);
   imshow( "Linear Blend", dst );
   waitKey(0);
   return 0;
}

4. 代码解释

因为我们要执行:

g(x)=(1α)f0(x)+αf1(x)g(x)=(1-\alpha )f_{0}(x)+\alpha f_{1}(x)

需要加载两张源图像(f0(x)f1(x)f_{0}(x)和f_{1}(x)):

 src1 = imread( samples::findFile("LinuxLogo.jpg") );
 src2 = imread( samples::findFile("WindowsLogo.jpg") );

使用了以下图片:LinuxLogo.jpgWindowsLogo.jpg

image.png

image.png

  • 警告

    由于要 计算 src1src2相加的和,所以要求它们必须有相同的大小(宽度和高度)和类型。

现在需要生成g(x)图像。为此,使用函数addWeighted() 非常方便:

beta = ( 1.0 - alpha );
addWeighted( src1, alpha, src2, beta, 0.0, dst);

因为addWeighted() 按以下公式计算结果:

dst=αsrc1+βsrc2+γdst=\alpha\cdot src1 +\beta \cdot src2+\gamma

在这种情况下,上面的代码中gamma参数是0.0。

创建窗口,显示图像并等待用户结束程序。

  imshow( "Linear Blend", dst );
  waitKey(0);

5. 结果

添加_Images_Tutorial_Result_Big.jpg

                                                                         [原文连接](https://docs.opencv.org/4.x/d5/dc4/tutorial_adding_images.html)