前言
图像混合将两张或多张图像按一定比例融合在一起,从而生成一张新的图像。OpenCV 提供的 addWeighted()
,可以实现这一功能。通过该函数,可以指定每张图像的权重,从而控制它们在最终图像中的比例。本篇博客将介绍图像混合的基本概念,并通过代码示例详细讲解 addWeighted()
函数的使用。
1.理论基础
图像混合可以通过线性加权的方式来实现。假设有两张图像src1
和 src2
,它们在某个像素点 I
的像素值分别为 src1(I)
和 src2(I)
,那么通过加权组合,可以得到混合后的像素值 dst(I)
,其计算公式为:
gamma
:是一个可选的常数偏移量,通常用于调整混合后图像的整体亮度。
saturate
:表示饱和运算,确保混合后的像素值 dst(I)
保持在有效的范围内(例如,对于8位图像,范围是0到255),防止值溢出或不足。
为了保证视觉一致性,通常alpha + beta = 1
。
2.代码实现
(1)图像读取
图像读取、展示和保存前面章节有介绍[OpenCV] 数字图像处理 C++ 学习——01图像的读取、加载和保存附完整代码(小白入门篇)
cv::Mat image1 = cv::imread("Linuxlogo.png");
cv::Mat image2 = cv::imread("opencvlogo.png");
// 检查图像是否成功读取
if (image1.empty() || image2.empty()) {
std::cerr << "Could not find or open the images" << std::endl;
return;
}
(2)addWeighted()函数
为了确保图像混合的效果,需要首先检查两张图像的尺寸是否一致,利用 addWeighted
函数按一定比例将它们混合在一起。注意:混合的图像大小尺寸要求一致。
// 检查两张图像的尺寸是否一致
if (image1.size() != image2.size()) {
std::cerr << "The images must be of the same size for blending" << std::endl;
return;
}
// 混合图像
cv::Mat blendedimage;
double alpha = 0.5; // 第一张图像的权重
double beta = 1- alpha; // 第二张图像的权重
cv::addWeighted(image1, alpha, image2, beta, 0.0, blendedimage);
// 显示结果
cv::namedWindow("blended image", cv::WINDOW_AUTOSIZE);
cv::imshow("blended image", blendedimage);
waitKey(0);
result
完整代码
#include<opencv2/opencv.hpp>
#include<highgui.hpp>
using namespace cv;
using namespace std;
void image_blended()
{
cv::Mat image1 = cv::imread("E:/teach/image_processing(opencv_c++)/images/01all/Linuxlogo.png");
cv::Mat image2 = cv::imread("E:/teach/image_processing(opencv_c++)/images/01all/opencvlogo.png");
// 检查图像是否成功读取
if (image1.empty() || image2.empty()) {
std::cerr << "Could not find or open the images" << std::endl;
return;
}
// 检查两张图像的尺寸是否一致
if (image1.size() != image2.size()) {
std::cerr << "The images must be of the same size for blending" << std::endl;
return;
}
cv::Mat blendedimage;
double alpha = 0.5;
double beta = 0.5;
cv::addWeighted(image1, alpha, image2, beta, 0.0, blendedimage);
cv::namedWindow("blended image", cv::WINDOW_AUTOSIZE);
cv::imshow("blended image", blendedimage);
waitKey(0);
}
int main()
{
image_blended();
return 0;
}