Direct Graphical Models  v.1.7.0
InferDense.cpp
1 #include "InferDense.h"
2 #include "IEdgeModel.h"
3 
4 namespace DirectGraphicalModels
5 {
6  namespace {
7  template<typename T>
8  void normalize(const Mat &src, Mat dst) {
9  if(dst.empty()) dst = Mat(src.size(), src.type());
10  for (int y = 0; y < src.rows; y++) {
11  const T *pSrc = src.ptr<T>(y);
12  T *pDst = dst.ptr<T>(y);
13  T sum = 0;
14  for (int x = 0; x < src.cols; x++) sum += pSrc[x];
15  if (sum > DBL_EPSILON)
16  for (int x = 0; x < src.cols; x++) pDst[x] = pSrc[x] / sum;
17  } // y
18  }
19 
20  template<typename T>
21  void myexp(const Mat &src, Mat &dst)
22  {
23  for (int y = 0; y < src.rows; y++) {
24  const T *pSrc = src.ptr<float>(y);
25  T *pDst = dst.ptr<float>(y);
26 
27  // Find the max and subtract it so that the exp doesn't explode
28  T max = pSrc[0];
29  for (int x = 1; x < src.cols; x++)
30  if (pSrc[x] > max) max = pSrc[x];
31 
32  for (int x = 0; x < src.cols; x++)
33  pDst[x] = expf(pSrc[x] - max);
34  } // y
35  }
36  }
37 
38  void CInferDense::infer(unsigned int nIt)
39  {
40  // ====================================== Initialization ======================================
41  Mat nodePotentials = getGraphDense().getNodePotentials();
42  Mat nodePotentials0 = nodePotentials.clone();
43  Mat temp = Mat(nodePotentials.size(), nodePotentials.type());
44  Mat tmp;
45 
46  // =================================== Calculating potentials ==================================
47  for (unsigned int i = 0; i < nIt; i++) {
48 #ifdef DEBUG_PRINT_INFO
49  if (i == 0) printf("\n");
50  if (i % 5 == 0) printf("--- It: %d ---\n", i);
51 #endif
52  normalize<float>(nodePotentials, nodePotentials);
53 
54  // Add up all pairwise potentials
55  temp.setTo(1);
56  for (auto &edgePotModel : getGraphDense().getEdgeModels()) {
57  edgePotModel->apply(nodePotentials, tmp); // tmp = f(pot_i)
58  multiply(temp, tmp, temp); // temp *= exp(tmp)
59  }
60 
61  multiply(nodePotentials0, temp, nodePotentials); // pot_(i+1) = pot_0 * next
62  } // iter
63  }
64 }
Mat getNodePotentials(void) const
Returns the container with node potentials.
Definition: GraphDense.h:54
CGraphDense & getGraphDense(void) const
Returns the dense graph.
Definition: InferDense.h:36
virtual void infer(unsigned int nIt=1)
Inference.
Definition: InferDense.cpp:38