矩阵边际化(边际分布)

时间:2014-10-30 09:03:09

标签: c++ opencv matrix

我想从两个矩阵中边缘化以获得第三个矩阵。 基本上,我有两个大小为(4x1)的Mat对象,我想边缘化它们以获得行标准化的第三个4乘4矩阵。这是通过获取第一个Mat对象的第一行并与第二个Mat对象的每一行相乘来填充第三个4x4 Mat的第一行,每个行元素乘以除以该行的总和,如下图所示。还有here。 找到我到目前为止所采取的以下编码步骤并得到一点堆栈.... Diagrammatic illustration

const int nStates = 9;
register int iii, jjj;
float mMatrix[nStates][3] = {1,2,3,4,5,6,7,8,9};


//Pixelwise transitions
Mat nPot1 = Mat(nStates, 1, CV_32FC1,mMatrix );
Mat nPot2 = Mat(nStates, 1, CV_32FC1,mMatrix );
Mat NodeTransitions(nStates, nStates, CV_32FC1); NodeTransitions.setTo(Scalar(1.0f));
float fN1;
for( iii = 0; iii < nStates; iii++){
    float * pPot1 = nPot1.ptr<float>(iii);
    float * pPot2 = nPot2.ptr<float>(iii);
    float * pNodeTrans = NodeTransitions.ptr<float>(iii);
    //nPot1.at<float>(iii,0);
    //nPot2.at<float>(iii,0);
    float sum = 0;
    for (int i =0; i < nStates; i++){
        fN1 =  pPot1[i]*pPot2[iii];
        cout << fN1 << "\t";
    }
    for(jjj = 0; jjj < nStates; jjj++){
        //pNodeTrans[jjj] = fN1;
    }
    //cout << endl;
}

感谢。

1 个答案:

答案 0 :(得分:1)

只需计算外部产品,然后使用L1规范标准化每一行。

我会打电话给你的两个向量xy。然后计算R = x * y.t()并沿每行标准化R

在OpenCV中有Mat::dot函数,但它只为向量定义,你需要它用于矩阵(当你转换其中一个输入时,使它成为1xn矩阵或行向量)。

这意味着,您必须手动完成。您也可以使用Eigen进行这些矩阵乘法。考虑一下,如果你进行了大量的矩阵乘法,并且它们不代表图像等。

未经测试的代码:

const int nStates = 9;
float mMatrix[nStates][1] = {1,2,3,4,5,6,7,8,9};

//Pixelwise transitions
Mat nPot1 = Mat(nStates, 1, CV_32FC1,mMatrix );
Mat nPot2 = Mat(nStates, 1, CV_32FC1,mMatrix );
Mat NodeTransitions(nStates, nStates, CV_32FC1);
NodeTransitions.setTo(Scalar(1.0f)); // Why are you doing this?
float fN1;

// Pass one, compute outer product.
for (int row=0; row < nStates; row++) {
    for (int col=0; col < nStates; col++) {
        fN1 = nPot1.at<float>(row, 0) * nPot2.at<float>(col, 0);
        NodeTransitions.at<float>(row, col)  = fN1;
    }
}

// Pass two, normalise each row.
for (int row=0; row < nStates; row++) {
    // find sum of this row
    fN1 = 0; // using fN1 for sum now.
    for (int col=0; col < nStates; col++) {
        fN1 += NodeTransitions.at<float>(row, col);
    }
    // Now divide all elements in row by sum
    for (int col=0; col < nStates; col++) {
        // divide value at row,col by fN1.
        NodeTransitions.at<float>(row, col) /= fN1;
    }
}

评论效率

鉴于您nStates非常小,这段代码应该足够高效。看起来,你一下子就试图做所有这一切。没有必要。