Opencv 图像平滑基础二维离散卷积C++ API

//实现same卷积
# include <opencv2\core\core.hpp>
# include <opencv2\highgui\highgui.hpp>
# include<opencv2\imgproc\imgproc.hpp>
# include <iostream>
using namespace std;
using namespace cv;
template<class T>
void printMat(Mat matrix)
{
	for (int r = 0; r < matrix.rows; r++)
	{
		for (int c = 0; c < matrix.cols; c++)
		{
			if (typeid(T) == typeid(uchar)) {
				cout << (int)(matrix.at<T>(r, c)) << ",";
			}
			else
			{
				cout << (matrix.at<T>(r, c)) << ",";
			}
		}
		cout << endl;
	}
	cout << endl;
}
template<class T>
void printMatT(Mat matrix)
{
	for (int r = 0; r < matrix.rows; r++)
	{
		for (int c = 0; c < matrix.cols; c++)
		{
			cout << (matrix.at<T>(r, c)) << ",";
		}
		cout << endl;
	}
	cout << endl;
}
void conv2D(InputArray src, InputArray kernel, OutputArray dst, int ddepth, Point anchor = Point(-1, -1), int borderType = BORDER_DEFAULT)
{
	//卷积运算第一步:卷积核逆时针反转180度
	Mat kernelFlip;
	flip(kernel, kernelFlip, -1);
	//卷积运算第二步
	filter2D(src, dst, ddepth, kernelFlip, anchor, 0.0, borderType);
}
//可分离的离散二维卷积
void sepConv2D_Y_X(InputArray src, OutputArray src_kerY_kerX, int ddepth, InputArray kernelY, InputArray kernelX, Point anchor = Point(-1, -1), int borderType = BORDER_DEFAULT)
{
	//输入矩阵与垂直方向上的卷积核的卷积
	Mat src_kerY;
	conv2D(src, kernelY, src_kerY, ddepth, anchor, borderType);
	//和水平方向的卷积核卷积
	conv2D(src_kerY, kernelX, src_kerY_kerX, ddepth, anchor, borderType);
}
int main()
{
	Mat I = (Mat_<float>(2, 2) << 1, 2, 3, 4);
	Mat K = (Mat_<float>(2, 2) << -1, -2, 2, 1);
	Mat c_same;
	conv2D(I, K, c_same, CV_32FC1, Point(0, 0), BORDER_CONSTANT);
	printMatT<float>(c_same);
	//输入矩阵
	Mat src = (Mat_<float>(5, 5) << 1, 2, 3, 10, 12,
		32, 43, 12, 4, 190,
		12, 234, 78, 0, 12,
		43, 90, 32, 8, 90,
		71, 12, 4, 98, 123);
	//卷积核
	Mat kernel = (Mat_<float>(3, 3) << 1, 0, -1, 1, 0, -1, 1, 0, -1);
	//same 卷积
	Mat c_same1;
	conv2D(src, kernel, c_same1, CV_32FC1, Point(-1, -1), 4);
	printMatT<float>(c_same1);
	//利用卷积核的分离特性计算
	Mat kernel1 = (Mat_<float>(1, 3) << 1, 0, -1);
	Mat kernel2 = (Mat_<float>(3, 1) << 1, 1, 1);
	Mat c_same2;
	sepConv2D_Y_X(src, c_same2, CV_32FC1, kernel1, kernel2);
	printMatT<float>(c_same2);

}
posted @ 2019-10-15 09:30  消灭猕猴桃  阅读(193)  评论(0编辑  收藏  举报