OpenCV(6): 圖像線性混合


注:轉載請標明原文出處鏈接:https://xiongyiming.blog.csdn.net/article/details/106938682


圖像線性混合的理論表達式爲:

dst(x)=f(src1(x)alpha+src1(x)beta)+gammadst(x) = f\left( {src1(x) \cdot alpha + src1(x) \cdot beta} \right) + gamma


OpenCV中線性混合使用 addWeighted() 函數,其用法爲:
addWeighted(src1, alpha, src2, beta, gamma, dst);

其中各個參數分別爲:
參數src1:輸入圖像src1
參數alpha:輸入圖像src1的alpha值
參數src2:輸入圖像 src2
參數beta:輸入圖像src2的beta值
參數gamma:gamma值
參數dst:輸出混合圖像


注:兩張圖像的大小和類型必須一致纔可以進行混合操作。



代碼示例

#include <opencv2/core/core.hpp> 
#include <opencv2/imgcodecs.hpp> 
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/highgui/highgui_c.h>

#include <iostream>
#include <math.h>




using namespace cv;
using namespace std;
int main(int argc, char** args) {
	Mat src = imread("ZXP1.jpg", IMREAD_UNCHANGED);
	if (src.empty()) {
		cout << "could not find the image resource..." << std::endl;
		return -1;
	}
	namedWindow("Original Image", CV_WINDOW_AUTOSIZE);
	imshow("Original Image", src);


	
	Mat dst;
	dst.create(src.size(), src.type());//或者用dst = Mat(src.size(), src.type());
	int height = src.rows;
	int width = src.cols;
	
	for (int row = 0; row < height; row++)
	{
		for (int col = 0; col < width; col++)
		{

				int b = src.at<Vec3b>(row, col)[0];
				int g = src.at<Vec3b>(row, col)[1];
				int r = src.at<Vec3b>(row, col)[2];

				dst.at<Vec3b>(row, col)[0] = b - 50;
				dst.at<Vec3b>(row, col)[1] = g ;
				dst.at<Vec3b>(row, col)[2] = r + 50;
		
		}
	}
	

	namedWindow("Output Image_1", CV_WINDOW_AUTOSIZE);
	imshow("Output Image_1", dst);
	
	Mat dst_mixed;
	double alpha = 0.5;
	if (src.rows == dst.rows && src.cols == dst.cols && src.type() == dst.type())
	{
		addWeighted(src, alpha, dst, (1.0 - alpha), 0.0, dst_mixed); //圖像混合
		namedWindow("Output Image_2", CV_WINDOW_AUTOSIZE);
		imshow("Output Image_2", dst_mixed);

	}

	else
	{
		cout << "圖像尺寸不一致" << endl;
		return -1;
	}


	waitKey(0);

	return 0;
}

運行結果

在這裏插入圖片描述






參考資料

[1] https://edu.51cto.com/course/7521.html?source=so



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章