Commit 3ced73347839256be3a1cb422321e965f97b8c89

Authored by Brendan Klare
1 parent 82fa59c1

Eigen convenience functions

openbr/core/eigenutils.cpp
... ... @@ -67,3 +67,12 @@ void printEigen(Eigen::MatrixXf X) {
67 67 void printSize(Eigen::MatrixXf X) {
68 68 qDebug() << "Rows=" << X.rows() << "\tCols=" << X.cols();
69 69 }
  70 +
  71 +float eigMean(const Eigen::MatrixXf& x) {
  72 + return x.array().sum() / (x.rows() * x.cols());
  73 +}
  74 +
  75 +float eigStd(const Eigen::MatrixXf& x) {
  76 + float mean = eigMean(x);
  77 + return sqrt((x.array() - mean).pow(2).sum() / (x.cols() * x.rows()));
  78 +}
... ...
openbr/core/eigenutils.h
... ... @@ -67,4 +67,55 @@ inline QDataStream &amp;operator&gt;&gt;(QDataStream &amp;stream, Eigen::Matrix&lt; _Scalar, _Row
67 67 return stream;
68 68 }
69 69  
  70 +/*Compute the mean of the each column (dim == 1) or row (dim == 2)
  71 + of the matrix*/
  72 +template<typename T>
  73 +Eigen::MatrixBase<T> eigMean(const Eigen::MatrixBase<T>& x,int dim)
  74 +{
  75 + if (dim == 1) {
  76 + Eigen::MatrixBase<T> y(1,x.cols());
  77 + for (int i = 0; i < x.cols(); i++)
  78 + y(i) = x.col(i).sum() / x.rows();
  79 + return y;
  80 + } else if (dim == 2) {
  81 + Eigen::MatrixBase<T> y(x.rows(),1);
  82 + for (int i = 0; i < x.rows(); i++)
  83 + y(i) = x.row(i).sum() / x.cols();
  84 + return y;
  85 + }
  86 + qFatal("A matrix can only have two dimensions");
  87 +}
  88 +
  89 +/*Compute the element-wise mean*/
  90 +float eigMean(const Eigen::MatrixXf& x);
  91 +/*Compute the element-wise mean*/
  92 +float eigStd(const Eigen::MatrixXf& x);
  93 +
  94 +/*Compute the std dev of the each column (dim == 1) or row (dim == 2)
  95 + of the matrix*/
  96 +template<typename T>
  97 +Eigen::MatrixBase<T> eigStd(const Eigen::MatrixBase<T>& x,int dim)
  98 +{
  99 + Eigen::MatrixBase<T> mean = eigMean(x, dim);
  100 + if (dim == 1) {
  101 + Eigen::MatrixBase<T> y(1,x.cols());
  102 + for (int i = 0; i < x.cols(); i++) {
  103 + T value = 0;
  104 + for (int j = 0; j < x.rows(); j++)
  105 + value += pow(y(j, i) - mean(i), 2);
  106 + y(i) = sqrt(value / (x.rows() - 1));
  107 + }
  108 + return y;
  109 + } else if (dim == 2) {
  110 + Eigen::MatrixBase<T> y(x.rows(),1);
  111 + for (int i = 0; i < x.rows(); i++) {
  112 + T value = 0;
  113 + for (int j = 0; j < x.cols(); j++)
  114 + value += pow(y(i, j) - mean(j), 2);
  115 + y(i) = sqrt(value / (x.cols() - 1));
  116 + }
  117 + return y;
  118 + }
  119 + qFatal("A matrix can only have two dimensions");
  120 +}
70 121 #endif // EIGENUTILS_H
... ...