【OpenCV3】图像通道分离与合并——cv::split()与cv::merge()详解

在图像处理中,尤其是处理多通道图像时,有时需要对各个通道进行分离,分别处理;有时还需要对分离处理后的各个通道进行合并,重新合并成一个多通道的图像。opencv2和opencv3中实现图像通道的合并与分离的函数分别是cv::split()和cv::merge()。


1、多通道图像的分离

cv::split()的具体调用方法如下:

void cv::split(
	const cv::Mat& mtx, //输入图像
	vector& mv // 输出的多通道序列(n个单通道序列)
);

2、图像多个通道的合并

cv::merge()的具体调用方法如下:

void merge(
	const vector& mv, // 输入的多通道序列(n个单通道序列)
	cv::OutputArray dst // 输出图像,包含mv
);


代码示例如下:

#include 

int main()
{
	cv::Mat src = imread("lenna.jpg", cv::IMREAD_COLOR);
	cv::imshow("src", src);

	// Split the image into different channels
	std::vector rgbChannels(3);
	split(src, rgbChannels);

	// Show individual channels
	cv::Mat blank_ch, fin_img;
	blank_ch = cv::Mat::zeros(cv::Size(src.cols, src.rows), CV_8UC1);

	// Showing Red Channel
	// G and B channels are kept as zero matrix for visual perception
	std::vector channels_r;
	channels_r.push_back(blank_ch);
	channels_r.push_back(blank_ch);
	channels_r.push_back(rgbChannels[2]);

	/// Merge the three channels
	cv::merge(channels_r, fin_img);
	cv::imshow("R", fin_img);
	

	// Showing Green Channel
	std::vector channels_g;
	channels_g.push_back(blank_ch);
	channels_g.push_back(rgbChannels[1]);
	channels_g.push_back(blank_ch);
	cv::merge(channels_g, fin_img);
	cv::imshow("G", fin_img);
	

	// Showing Blue Channel
	std::vector channels_b;
	channels_b.push_back(rgbChannels[0]);
	channels_b.push_back(blank_ch);
	channels_b.push_back(blank_ch);
	cv::merge(channels_b, fin_img);
	cv::imshow("B", fin_img);
	
	cv::waitKey(0);
	return 0;
}


显示结果:

【OpenCV3】图像通道分离与合并——cv::split()与cv::merge()详解_第1张图片


2017.04.27


你可能感兴趣的:(图像处理,机器视觉,OpenCV)