OpenCV在矩阵上的卷积

转载请注明出处!!!http://blog.csdn.net/zhonghuan1992

OpenCV在矩阵上的卷积




         在openCV官网上说是戴面具,事实上就是又一次计算一下矩阵中的每个value,那么怎么计算呢,依据该像素点的周围信息,用一个加权的公式来进行计算。那么如今就要看,周围的信息是怎样被加权的。让我们想一下这种方式,请看以下的公式:

        

         上面的公式就是根据当前像素点的值和四个邻居的值,更新一下。相当于原来矩阵每一块3*3的小矩阵和M进行想乘一样。

         在程序中,我们对该公式进行编程的话,会是以下的代码。

#include <opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include <iostream>
#include <sstream>

using namespace std;
using namespace cv;

void Sharpen(const Mat& myImage, Mat& Result)
{
	CV_Assert(myImage.depth() == CV_8U);  // accept only uchar images,这里确保我们接受的图片的格式

	Result.create(myImage.size(), myImage.type()); //依据myImage的size和type来创建矩阵。
	const int nChannels = myImage.channels();//获取图片的channel

	for (int j = 1; j < myImage.rows - 1; ++j)
	{
		const uchar* previous = myImage.ptr<uchar>(j - 1);//获取i,j位置上i行,i-1行和i+1行,
		const uchar* current = myImage.ptr<uchar>(j);
		const uchar* next = myImage.ptr<uchar>(j + 1);

		uchar*output = Result.ptr<uchar>(j);

		for (int i = nChannels; i < nChannels * (myImage.cols - 1); ++i)
		{
			*output++ = saturate_cast<uchar>(5 * current[i]
				- current[i - nChannels] - current[i + nChannels] - previous[i] - next[i]);//这里依据公式计算,之所以是i-nChannels是由于矩阵的存储格式,
			//  详细看这里http://blog.csdn.net/zhonghuan1992/article/details/38408939
		}
	}

	//对于图像的边界部分,上面的公式并不作用于这里,在这样的情况下,能够把边界值都设为0
	Result.row(0).setTo(Scalar(0));
	Result.row(Result.rows - 1).setTo(Scalar(0));
	Result.col(0).setTo(Scalar(0));
	Result.col(Result.cols - 1).setTo(Scalar(0));
}
int main()
{
	String str = "zh.png";
	Mat I, J;
	//I = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);
	I = imread(str, CV_LOAD_IMAGE_COLOR);

	Sharpen(I, J);
	imshow("", J);
	waitKey();

	return 0;
}


转换前的图像:

        

卷积后的图像:

        

        

         能够自行比較一下这两幅图片的不同之处。

The filter2D function:

         由于上面的过程在图像处理中太常见了,openCV提供了函数对这样的操作的支持。在卷积前,你要选择一个矩阵,看上面的公式,就是那个M,要确定那个M。

Mat kern = (Mat_<char>(3, 3) << 0, -1, 0,
		-1, 5, -1,
		0, -1, 0);


         然后使用filter2D函数。

filter2D(I, K, I.depth(), kern);


         经过比較,在我的电脑上,第一种方式用时21毫秒,另外一种方式用时仅7毫秒。

         程序完整代码可从这里下载:

原文地址:https://www.cnblogs.com/bhlsheji/p/4294420.html