问题描述
|
有一个单通道灰度IplImage,其协方差矩阵要计算。 SO上确实有一个类似的问题,但是没有人回答,代码也有很大不同。
这是引发“未处理的异常”的代码:
int calcCovar( IplImage *src,float* dst,int w )
{
// Input matrix size
int rows = w;
int cols = w;
int i,j;
CvScalar se;
float *a;
a = (float*)malloc( w * w * sizeof(float) );
long int k=0;
//image pixels into 1D array
for(i = 0; i < w; ++i)
{
for(j = 0; j < w; ++j)
{
se = cvGet2D(src,i,j);
a[k++] = (float)se.val[0];
}
}
CvMat input = cvMat(w,w,CV_32FC1,a); //Is this the right way to format input pixels??
// Covariance matrix is N x N,// where N is input matrix column size
const int n = w;
// Output variables passed by reference
CvMat* output = cvCreateMat(n,n,CV_32FC1);
CvMat* meanvec = cvCreateMat(1,rows,CV_32FC1);
// Calculate covariance matrix - error is here!!
cvCalcCovarMatrix((const void **) &input,output,meanvec,CV_COVAR_norMAL);
k = 0;
//Show result
cout << \"Covariance matrix:\" << endl;
for(i=0; i<n; i++) {
for(j=0; j<n; j++) {
cout << \"(\" << i << \",\" << j << \"): \";
printf (\"%f \",cvGetReal2D(output,j) / (rows - 1));
dst[k++] = cvGetReal2D(output,j) / (rows - 1);
//cout << \"\\t\";
}
cout << endl;
}
return(0);
}
解决方法
请阅读手册中有关此功能的信息。如果将值存储在单个矩阵“输入”中,则第二个功能参数不得为“行”。第二个参数用于说明您在第一个参数中传递了多少个矩阵。您仅传递了一个矩阵\'input \'。 Segfault不足为奇。