图像拉普拉斯金字塔融合(Laplacian Pyramid Blending)

本文将介绍图像金字塔以及拉普拉斯融合的相关知识。

图像金字塔

================================================

一般的的线性变换通过将一幅图像乘以transform函数分成不同的components。离散傅里叶变换、离散余弦变换、奇异值分解 和 小波变换 都以拉普拉斯金字塔和其他奖采样变换为简单基础。


真实数字图像包括一系列物体和特征(不同scales、orientation和角度下的lines, shapes, patterns, edges)


the simple process for a pyramid with an arbitrary number of levels:

平滑图像->将图像进行下采样(常取采样率r=2) 而获得,同样的操作反复做,金字塔层数逐渐上升,空间采样密度逐渐下降。(如下图)这个多维表示就像一个金字塔,其中fi表示图像,li表示低通滤波结果,hi表示高通滤波结果。li / hi通过将图像与高通/低通滤波器卷积而得。

与之相反,金字塔重建通过上采样获得。


以图像金字塔为基础的双边滤波器是一个图像细节增强和操作的很好的框架。

图像融合(Image Blending)

================================================

原理:

1.建立两幅图像的拉普拉斯金字塔
2.求高斯金字塔(掩模金字塔-为了拼接左右两幅图像)
3. 进行拼接blendLapPyrs() ; 在每一层上将左右laplacian图像直接拼起来得结果金字塔resultLapPyr
4.重建图像: 从最高层结果图
//将左右laplacian图像拼成的resultLapPyr金字塔中每一层,从上到下插值放大并和下一层相加,即得blend图像结果(reconstructImgFromLapPyramid)


Code:
配置环境:
VS2010+opencv 2.3.1(2.2版本以上均可)

#include "opencv2/opencv.hpp"
using namespace cv;

/************************************************************************/
/* 说明:
*金字塔从下到上依次为 [0,1,...,level-1] 层
*blendMask 为图像的掩模
*maskGaussianPyramid为金字塔每一层的掩模
*resultLapPyr 存放每层金字塔中直接用左右两图Laplacian变换拼成的图像
*/
/************************************************************************/


class LaplacianBlending {
private:
	Mat_<Vec3f> left;
	Mat_<Vec3f> right;
	Mat_<float> blendMask;

	vector<Mat_<Vec3f> > leftLapPyr,rightLapPyr,resultLapPyr;//Laplacian Pyramids
	Mat leftHighestLevel, rightHighestLevel, resultHighestLevel;
	vector<Mat_<Vec3f> > maskGaussianPyramid; //masks are 3-channels for easier multiplication with RGB

	int levels;

	void buildPyramids() {
		buildLaplacianPyramid(left,leftLapPyr,leftHighestLevel);
		buildLaplacianPyramid(right,rightLapPyr,rightHighestLevel);
		buildGaussianPyramid();
	}

	void buildGaussianPyramid() {//金字塔内容为每一层的掩模
		assert(leftLapPyr.size()>0);

		maskGaussianPyramid.clear();
		Mat currentImg;
		cvtColor(blendMask, currentImg, CV_GRAY2BGR);//store color img of blend mask into maskGaussianPyramid
		maskGaussianPyramid.push_back(currentImg); //0-level

		currentImg = blendMask;
		for (int l=1; l<levels+1; l++) {
			Mat _down;
			if (leftLapPyr.size() > l)
				pyrDown(currentImg, _down, leftLapPyr[l].size());
			else
				pyrDown(currentImg, _down, leftHighestLevel.size()); //lowest level

			Mat down;
			cvtColor(_down, down, CV_GRAY2BGR);
			maskGaussianPyramid.push_back(down);//add color blend mask into mask Pyramid
			currentImg = _down;
		}
	}

	void buildLaplacianPyramid(const Mat& img, vector<Mat_<Vec3f> >& lapPyr, Mat& HighestLevel) {
		lapPyr.clear();
		Mat currentImg = img;
		for (int l=0; l<levels; l++) {
			Mat down,up;
			pyrDown(currentImg, down);
			pyrUp(down, up,currentImg.size());
			Mat lap = currentImg - up;
			lapPyr.push_back(lap);
			currentImg = down;
		}
		currentImg.copyTo(HighestLevel);
	}

	Mat_<Vec3f> reconstructImgFromLapPyramid() {
		//将左右laplacian图像拼成的resultLapPyr金字塔中每一层
		//从上到下插值放大并相加,即得blend图像结果
		Mat currentImg = resultHighestLevel;
		for (int l=levels-1; l>=0; l--) {
			Mat up;

			pyrUp(currentImg, up, resultLapPyr[l].size());
			currentImg = up + resultLapPyr[l];
		}
		return currentImg;
	}

	void blendLapPyrs() {
		//获得每层金字塔中直接用左右两图Laplacian变换拼成的图像resultLapPyr
		resultHighestLevel = leftHighestLevel.mul(maskGaussianPyramid.back()) +
			rightHighestLevel.mul(Scalar(1.0,1.0,1.0) - maskGaussianPyramid.back());
		for (int l=0; l<levels; l++) {
			Mat A = leftLapPyr[l].mul(maskGaussianPyramid[l]);
			Mat antiMask = Scalar(1.0,1.0,1.0) - maskGaussianPyramid[l];
			Mat B = rightLapPyr[l].mul(antiMask);
			Mat_<Vec3f> blendedLevel = A + B;

			resultLapPyr.push_back(blendedLevel);
		}
	}

public:
	LaplacianBlending(const Mat_<Vec3f>& _left, const Mat_<Vec3f>& _right, const Mat_<float>& _blendMask, int _levels)://construct function, used in LaplacianBlending lb(l,r,m,4);
	  left(_left),right(_right),blendMask(_blendMask),levels(_levels)
	  {
		  assert(_left.size() == _right.size());
		  assert(_left.size() == _blendMask.size());
		  buildPyramids();	//construct Laplacian Pyramid and Gaussian Pyramid
		  blendLapPyrs();	//blend left & right Pyramids into one Pyramid
	  };

	  Mat_<Vec3f> blend() {
		  return reconstructImgFromLapPyramid();//reconstruct Image from Laplacian Pyramid
	  }
};

Mat_<Vec3f> LaplacianBlend(const Mat_<Vec3f>& l, const Mat_<Vec3f>& r, const Mat_<float>& m) {
	LaplacianBlending lb(l,r,m,4);
	return lb.blend();
}

int main() {
	Mat l8u = imread("left.png");
	Mat r8u = imread("right.png");

	imshow("left",l8u); 
	imshow("right",r8u);

	Mat_<Vec3f> l; l8u.convertTo(l,CV_32F,1.0/255.0);//Vec3f表示有三个通道,即 l[row][column][depth]
	Mat_<Vec3f> r; r8u.convertTo(r,CV_32F,1.0/255.0);
	/*****************    void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;******************/
	/* Performs linear transformation on every source array element:
	dst(x,y,c) = scale*src(x,y,alpha)+beta.
	Arbitrary combination of input and output array depths are allowed
	(number of channels must be the same), thus the function can be used
	for type conversion */

	//create blend mask matrix m
	Mat_<float> m(l.rows,l.cols,0.0);					//将m全部赋值为0
	m(Range::all(),Range(0,m.cols/2)) = 1.0;	//取m全部行&[0,m.cols/2]列,赋值为1.0

	Mat_<Vec3f> blend = LaplacianBlend(l, r, m);
	imshow("blended",blend);

	waitKey(0);
	return 0;
}



<think>我们正在讨论OpenCV中的拉普拉斯金字塔融合Laplacian Pyramid Blending)方法。根据用户提供的引用内容,我们可以总结出拉普拉斯金字塔融合的基本步骤。同时,用户希望了解其原理和使用方法。 拉普拉斯金字塔融合的基本原理: 1. 拉普拉斯金字塔是对图像的高频信息(细节)的多尺度表示。金字塔的每一层都代表了不同尺度下的细节信息,底层是高频细节,顶层是低频概貌。 2. 融合时,对两幅图像分别构建拉普拉斯金字塔和高斯金字塔(用于掩模)。然后,根据掩模金字塔(通常是一个渐变过渡的权重图)将两幅图像拉普拉斯金字塔在同一层上按照权重混合,得到融合后的拉普拉斯金字塔。 3. 最后,通过将融合后的拉普拉斯金字塔从顶层到底层逐层重建(上采样并叠加),得到最终的融合图像。 具体步骤(参考引用[1][2][3][4]): 1. 对两幅待融合图像(假设为A和B)分别构建高斯金字塔拉普拉斯金字塔。 2. 构建一个掩模(mask)金字塔,该掩模用于指定融合的过渡区域(例如,左图权重从1渐变到0,右图权重从0渐变到1)。这个掩模也需要构建高斯金字塔(因为掩模金字塔需要与拉普拉斯金字塔的每一层相匹配)。 3. 在每一层拉普拉斯金字塔上,根据该层的掩模权重将两幅图像拉普拉斯金字塔进行混合:融合后的拉普拉斯金字塔层 = A的拉普拉斯层 * 掩模权重 + B的拉普拉斯层 * (1-掩模权重)。 4. 将融合后的拉普拉斯金字塔从最高层开始重建:从最高层(最小尺寸)开始,将其上采样到下一层的大小,然后与下一层的融合拉普拉斯金字塔图像相加,重复这个过程直到最底层,得到最终的融合图像。 在OpenCV中,我们可以使用以下函数来实现: - `cv2.pyrDown`:构建高斯金字塔(下采样) - `cv2.pyrUp`:上采样(用于重建) - 拉普拉斯金字塔可以通过高斯金字塔计算:拉普拉斯层 = 当前层高斯金字塔 - 当前层高斯金字塔上采样后再下采样的结果(实际上,拉普拉斯金字塔的每一层是高斯金字塔的当前层减去上一层上采样并插值的结果) 但是,OpenCV并没有直接提供拉普拉斯金字塔融合的函数,我们需要自己实现。 下面我们将用步骤和代码来说明: 步骤1:构建两幅图像的高斯金字塔 步骤2:由高斯金字塔构建拉普拉斯金字塔 步骤3:构建掩模的高斯金字塔(掩模需要先定义,比如一个从左到右渐变的权重图) 步骤4:用掩模金字塔在每一层上融合两幅图像拉普拉斯金字塔 步骤5:重建图像(从融合后的拉普拉斯金字塔重建) 注意:在构建金字塔之前,需要确保两幅图像尺寸相同,并且是2的幂次(或者至少能够被多次下采样)。如果尺寸不满足,可能需要调整。 代码示例(基于引用[5]中的OpenCV环境,使用OpenCV2.3.1以上版本): ```python import cv2 import numpy as np def laplacian_pyramid_blending(img1, img2, mask, levels=5): # 步骤1:构建两幅图像的高斯金字塔 G1 = img1.copy() G2 = img2.copy() gpA = [G1] gpB = [G2] for i in range(levels): G1 = cv2.pyrDown(G1) G2 = cv2.pyrDown(G2) gpA.append(np.float32(G1)) gpB.append(np.float32(G2)) # 步骤2:构建拉普拉斯金字塔 lpA = [gpA[levels-1]] # 高斯金字塔的顶层也是拉普拉斯金字塔的顶层 for i in range(levels-1, 0, -1): GE = cv2.pyrUp(gpA[i]) # 调整GE的尺寸与gpA[i-1]相同,因为上采样后尺寸可能差1个像素 rows, cols, dpt = gpA[i-1].shape GE = cv2.resize(GE, (cols, rows)) L = np.subtract(gpA[i-1], GE) lpA.append(L) lpA.reverse() # 现在拉普拉斯金字塔从底层到顶层排列(0层为最底层) lpB = [gpB[levels-1]] for i in range(levels-1, 0, -1): GE = cv2.pyrUp(gpB[i]) rows, cols, dpt = gpB[i-1].shape GE = cv2.resize(GE, (cols, rows)) L = np.subtract(gpB[i-1], GE) lpB.append(L) lpB.reverse() # 步骤3:构建掩模的高斯金字塔 # 首先将mask转换为0~1之间的浮点数,并使其与图像尺寸相同(单通道) mask = mask.astype(np.float32) mask = mask / 255.0 # 构建掩模的高斯金字塔 gpM = [mask] for i in range(levels): mask = cv2.pyrDown(mask) gpM.append(mask.astype(np.float32)) gpM.reverse() # 反转,使得0层为最底层(原始尺寸),然后随着层数增加尺寸减小 # 步骤4:融合拉普拉斯金字塔 lpAB = [] for la, lb, gm in zip(lpA, lpB, gpM): # 将掩模扩展为3通道(如果是彩色图像) gm3 = cv2.merge([gm, gm, gm]) # 融合:img1 * mask + img2 * (1-mask) blended = la * gm3 + lb * (1 - gm3) lpAB.append(blended) # 步骤5:重建图像 # 从融合金字塔的顶层(最小图像)开始重建 img_reconstructed = lpAB[0] for i in range(1, levels): img_reconstructed = cv2.pyrUp(img_reconstructed) rows, cols, dpt = lpAB[i].shape img_reconstructed = cv2.resize(img_reconstructed, (cols, rows)) img_reconstructed = np.add(img_reconstructed, lpAB[i]) # 裁剪到0-255范围,并转换为uint8 img_reconstructed = np.clip(img_reconstructed, 0, 255) return img_reconstructed.astype(np.uint8) # 读取两幅图像和掩模 img1 = cv2.imread('apple.jpg') img2 = cv2.imread('orange.jpg') # 创建一个掩模,假设我们想要在中间融合,左边是img1,右边是img2 # 掩模:左半部分为1(白色),右半部分为0(黑色),中间有过渡 mask = np.zeros((img1.shape[0], img1.shape[1]), dtype=np.uint8) mask[:, :img1.shape[1]//2] = 255 # 左半部分为白色,右半部分为黑色 # 为了平滑过渡,我们可以对掩模进行高斯模糊 mask = cv2.GaussianBlur(mask, (99,99), 0) # 进行融合 levels = 5 # 金字塔层数 blended = laplacian_pyramid_blending(img1, img2, mask, levels) # 显示结果 cv2.imshow('Blended', blended) cv2.waitKey(0) cv2.destroyAllWindows() ``` 注意:上述代码中,我们假设输入图像是彩色图像(三通道)。掩模是单通道的,我们在融合时将其扩展为三通道。 原理说明: 拉普拉斯金字塔融合之所以能获得无缝融合,是因为它在不同频率段上分别进行融合。在低频部分(金字塔顶层)我们使用较大的过渡区域(因为掩模的高斯金字塔顶层是模糊的,所以权重变化缓慢),而在高频部分(金字塔底层)我们使用较小的过渡区域(掩模底层较清晰,权重变化快)。这样,在融合时,低频信息(如颜色)过渡平缓,而高频信息(如边缘)过渡锐利,从而避免了明显的接缝。 此外,用户提供的引用[3]中提到,在最高层(顶层)还需要将两幅图像的顶层高斯金字塔(即最模糊的图像)按照掩模的顶层进行融合。但在我们的代码中,拉普拉斯金字塔的顶层就是高斯金字塔的顶层,所以我们在融合拉普拉斯金字塔时已经包含了顶层的融合。 最后,我们生成几个相关问题: §§相关问题§§ 1. 拉普拉斯金字塔融合与直接拼接融合相比有什么优势? 2. 如何选择拉普拉斯金字塔的层数? 3. 在OpenCV中,除了拉普拉斯金字塔融合,还有哪些图像融合方法? 4. 拉普拉斯金字塔融合在哪些实际应用中被使用?</think>### OpenCV中拉普拉斯金字塔融合的原理与实现 拉普拉斯金字塔融合是一种多尺度图像融合技术,通过分离图像的不同频率成分实现无缝拼接。其核心原理是利用**高斯金字塔分解图像**,再通过**拉普拉斯金字塔保留细节信息**,最后在多个尺度上实现平滑过渡[^2][^4]。 #### 核心步骤 1. **构建高斯金字塔**: $$ \begin{align*} G_0 &= I \\ G_{k} &= \text{pyrDown}(G_{k-1}) \end{align*} $$ 其中$I$是原始图像,`pyrDown`是下采样操作 2. **构建拉普拉斯金字塔**: $$ L_k = G_k - \text{pyrUp}(G_{k+1}) $$ 拉普拉斯层存储高频细节信息[^4] 3. **创建掩模金字塔**: ```python mask_pyramid = [cv2.pyrDown(mask) for _ in range(levels)] ``` 4. **分层融合**: $$ \text{Blended}_k = L_{A,k} \times \text{mask}_k + L_{B,k} \times (1 - \text{mask}_k) $$ 5. **重建图像**: $$ \begin{align*} R_{\text{top}} &= \text{Blended}_{\text{top}} \\ R_k &= \text{pyrUp}(R_{k+1}) + \text{Blended}_k \end{align*} $$ 从顶层开始逐层上采样并叠加[^1][^3] #### OpenCV实现代码 ```python import cv2 import numpy as np def laplacian_blend(imgA, imgB, mask, levels=4): # 构建高斯金字塔 GA = imgA.copy() GB = imgB.copy() GM = mask.copy() gpA = [GA] gpB = [GB] gpM = [GM] for _ in range(levels): GA = cv2.pyrDown(GA) GB = cv2.pyrDown(GB) GM = cv2.pyrDown(GM) gpA.append(GA) gpB.append(GB) gpM.append(GM) # 构建拉普拉斯金字塔 lpA = [gpA[levels]] lpB = [gpB[levels]] for i in range(levels, 0, -1): LA = cv2.subtract(gpA[i-1], cv2.pyrUp(gpA[i])) LB = cv2.subtract(gpB[i-1], cv2.pyrUp(gpB[i])) lpA.append(LA) lpB.append(LB) # 分层融合 LS = [] for la, lb, gm in zip(lpA, lpB, gpM[::-1]): ls = la * gm + lb * (1.0 - gm) LS.append(ls) # 重建图像 blended = LS[0] for i in range(1, levels+1): blended = cv2.pyrUp(blended) blended = cv2.add(blended, LS[i]) return blended # 使用示例 imgA = cv2.imread('left.jpg').astype(float) imgB = cv2.imread('right.jpg').astype(float) mask = np.zeros(imgA.shape[:2]) mask[:, :imgA.shape[1]//2] = 1 # 左半部分为1,右半部分为0 result = laplacian_blend(imgA, imgB, mask) cv2.imwrite('blended.jpg', result) ``` #### 关键优势 1. **多尺度融合**:高频部分快速过渡,低频部分缓慢过渡[^2] 2. **无缝拼接**:避免传统拼接的接缝问题 3. **细节保留**:拉普拉斯金字塔捕获不同尺度的边缘信息 #### 应用场景 - 全景图像拼接 - HDR图像合成 - 医学影像融合 - 纹理替换
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值