OpenCV实现Matlab的fspecial('gaussian',m,sigma) 生成高斯核

Matlab:
function K = kernal(sigma)
m = ceil(2*sigma+1);  
K = fspecial('gaussian',m,sigma);


VS2008 C++ OpenCV:

Mat gaussian_kernal(int sigma)			//sigma既是高斯核半径,又是真正的sigma
{
	int dim = ceil(2.0 * sigma + 1);	//高斯核大小为dim*dim
	Mat K(dim, dim, CV_32FC1);
	//生成二维高斯核
	float s2 = 2.0 * sigma * sigma;
	for(int i = (-sigma); i <= sigma; i++)
	{
		int m = i + sigma;
		for (int j = (-sigma); j <= sigma; j++)
		{
			int n = j + sigma;
			float v = exp(-(1.0*i*i + 1.0*j*j) / s2);
			K.ptr(m)[n] = v;
		}
	}
	Scalar all = sum(K);
	Mat gaussK;
	K.convertTo(gaussK, CV_32FC1, (1/all[0]));
	return gaussK;
}
//再来一个既含有高斯核直径kernelSize,又有单独的sigma的版本:
//double sigma0 = (halfSize - 1)/ 2.0;
Mat gaussian_kernal(int kernelSize, double sigma0)
{  
int halfSize = (kernelSize-1)/ 2;
Mat K(kernelSize, kernelSize, CV_32FC1);  

//生成二维高斯核  
double s2 = 2.0 * sigma0 * sigma0;  
for(int i = (-halfSize); i <= halfSize; i++)  
{  
int m = i + halfSize;  
for (int j = (-halfSize); j <= halfSize; j++)  
{  
int n = j + halfSize;  
float v = exp(-(1.0*i*i + 1.0*j*j) / s2);  
K.ptr(m)[n] = v;  
}  
}  
Scalar all = sum(K);  
Mat gaussK;  
K.convertTo(gaussK, CV_32FC1, (1/all[0]));  


return gaussK;  
}  

你可能感兴趣的:(C/C++)