3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

OpenCV(C++)チュートリアル:2枚の画像をブレンドする

Posted at

公式チュートリアルのAdding (blending) two images using OpenCVの要約。
筆者の環境はDebian 9

やること

画像のリニアブレンドを行う数式

g(x)=(1−α)f_0(x)+αf_1(x)

$f_0(x)$, $f_1(x)$がそれぞれ入力画像。$α$を0から1に動かすことで$f_0(x)$から$f_1(x)$へとフェード(クロスディゾルブ)する。
addWeighted()関数でできる。

コード

sample.cpp
# include "opencv2/imgcodecs.hpp"
# include "opencv2/highgui.hpp"
# include <iostream>
using namespace cv;
// ここでは"using namespace std;"しない。c++17のstd::betaとここで使う変数betaが衝突する。 
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;
   // ユーザの入力したalphaが0から1なら使う。
   if( input >= 0 && input <= 1 )
     { alpha = input; }
   src1 = imread( "../data/LinuxLogo.jpg" );
   src2 = imread( "../data/WindowsLogo.jpg" );
   if( src1.empty() ) { cout << "Error loading src1" << endl; return -1; }
   if( src2.empty() ) { cout << "Error loading src2" << endl; return -1; }
   beta = ( 1.0 - alpha );
   //ブレンドを行う
   addWeighted( src1, alpha, src2, beta, 0.0, dst);
   imshow( "Linear Blend", dst );
   waitKey(0);
   return 0;
}

LinuxLogo.jpg
LinuxLogo.jpg

WindowsLogo.jpg
WindowsLogo.jpg

注意:読み込んだsrc1とsrc2は加算するので、幅・高さ・型が一致している必要がある。

説明

上記コードで


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

ブレンドを行うaddWeighted()関数は

$dst=α⋅src1+β⋅src2+γ$

を計算する。ここでは$γ$は0.0。

コンパイル

g++ sample.cpp -I/usr/local/include/opencv2 -I/usr/local/include/opencv -L/usr/local/lib -lopencv_core -lopencv_imgcodecs -lopencv_highgui

result.jpg
こんな感じになる。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?