目标
在本教程中,您将了解:
•什么是线性混合以及为什么它是有用的;
•如何添加两个图像
理论
注:下面的解释属于Richard Szeliski的《计算机视觉:算法与应用》一书
在前面的教程中,我们已经了解了一些像素运算符。一个有趣的二元(双输入)运算符是。
线性混合运算符:g(x) = (1 - α)f0(x) + αf1(x)
通过改变α从0 到1该运算符可用于在两个图像或视频之间执行时间交叉刻划,
就像在幻灯片放映和电影制作中看到的(酷,嗯?)
代码实现:
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\core\core.hpp>
#include <opencv2\opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
Mat src1;
Mat src2;
Mat dst;
double alpha = 0.5;
double beta;
double input;
///请求用户输入alpha
std::cout << " Simple Linear Blender " << std::endl;
std::cout << "-----------------------" << std::endl;
std::cout << "* Enter alpha [0-1]: ";
std::cin >> input;
///如果在0和1之间,我们使用用户提供的alpha
if (input >= 0.0 && input <= 1.0)
{
alpha = input;
}
///读取图像(大小相同,类型相同)
src1 = imread("D:\\workplace\\Visual Studio\\2013\\OpenCV2.4.11\\pic_data\\LinuxLogo.jpg");
src2 = imread("D:\\workplace\\Visual Studio\\2013\\OpenCV2.4.11\\pic_data\\WindowsLogo.jpg");
if (!src1.data)
{
printf("Error loading src1 \n");
return -1;
}
if (!src2.data)
{
printf("Error loading src2 \n");
return -1;
}
///创建窗口
namedWindow("Linear Blend", 1);
beta = (1.0 - alpha);
addWeighted(src1, alpha, src2, beta, 0.0, dst);
imshow("Linear Blend", dst);
waitKey(0);
return 0;
}
运行效果:
解释
1.因为我们要实现:
g(x)=(1-α)f0(x)+αf1(x)
我们需要两个源图像(f0(x)和f1(x))。因此,我们以通常的方式装载它们:
src1=imread(“D:\workplace\VisualStudio\2013\OpenCV2.4.11\pic_data\LinuxLogo.jpg”);
src2=imread(“D:\workplace\VisualStudio\2013\OpenCV2.4.11\pic_data\WindowsLogo.jpg”);
警告:因为我们添加了src1和src2,所以它们必须具有相同的大小(宽度和高度)和
类型。
2.现在我们需要生成g(x)图像。为此,添加权重的函数非常方便:
beta = ( 1.0 - alpha );
addWeighted( src1, alpha, src2, beta, 0.0, dst);
直到addWeighted产生:
dst =α·src1 +β·src2 +γ
在这种情况下,γ参数是0.0在上面的代码中。
3.运行效果所示。创建窗口,显示图像并等待用户结束程序