cosine.cpp
Go to the documentation of this file.
1 #include "cosine.h"
2 
3 #include <cmath>
4 
5 #include <SimoxUtility/algorithm/string.h>
6 
8 
10 {
11  double
13  {
14  //this does only work for RGB images not RGBDepth at the moment!
15  int width = p1->getShape().at(0);
16  int height = p1->getShape().at(1);
17  int dimensions = p1->getShape().at(2);
18  ARMARX_CHECK(dimensions == p2->getShape().at(2));
19  if (dimensions > 3)
20  {
21  ARMARX_INFO << "Trying to calculate cosine similarity for more than 3 channels, only "
22  "first three channels will be looked at";
23  }
24  Eigen::MatrixXf m1r(width, height);
25  Eigen::MatrixXf m2r(width, height);
26  Eigen::MatrixXf m1g(width, height);
27  Eigen::MatrixXf m2g(width, height);
28  Eigen::MatrixXf m1b(width, height);
29  Eigen::MatrixXf m2b(width, height);
30 
31  auto image1 = p1->getDataAsVector();
32  auto image2 = p2->getDataAsVector();
33 
34 
35  for (int x = 0; x < width; x++)
36  {
37  for (int y = 0; y < height; y++)
38  {
39  //R-value matices:
40  int index = x + width * (y + 0 * height);
41  double element1 = image1.at(index);
42  double element2 = image2.at(index);
43  m1r(x, y) = element1;
44  m2r(x, y) = element2;
45  //G-value matices:
46  index = x + width * (y + 1 * height);
47  element1 = image1.at(index);
48  element2 = image2.at(index);
49  m1g(x, y) = element1;
50  m2g(x, y) = element2;
51  //B-value matices:
52  index = x + width * (y + 2 * height);
53  element1 = image1.at(index);
54  element2 = image2.at(index);
55  m1b(x, y) = element1;
56  m2b(x, y) = element2;
57  }
58  }
59 
60 
61  double dotProductR = (m1r.array() * m2r.array()).sum();
62  double normProductR = m1r.norm() * m2r.norm();
63  double cosineR = 1.0 - (dotProductR / normProductR);
64  //ARMARX_INFO << VAROUT(cosineR);
65 
66  double dotProductG = (m1g.array() * m2g.array()).sum();
67  double normProductG = m1g.norm() * m2g.norm();
68  double cosineG = 1.0 - (dotProductG / normProductG);
69  //ARMARX_INFO << VAROUT(cosineG);
70 
71  double dotProductB = (m1b.array() * m2b.array()).sum();
72  double normProductB = m1b.norm() * m2b.norm();
73  double cosineB = 1.0 - (dotProductB / normProductB);
74  //ARMARX_INFO << VAROUT(cosineB);
75 
76  return (cosineR + cosineG + cosineB) / 3;
77  }
78 
79 } // namespace armarx::aron::similarity
index
uint8_t index
Definition: EtherCATFrame.h:59
armarx::aron::similarity
Definition: cosine.cpp:9
armarx::aron::data::NDArrayPtr
std::shared_ptr< NDArray > NDArrayPtr
Definition: NDArray.h:46
ARMARX_CHECK
#define ARMARX_CHECK(expression)
Shortcut for ARMARX_CHECK_EXPRESSION.
Definition: ExpressionException.h:82
ARMARX_INFO
#define ARMARX_INFO
Definition: Logging.h:181
armarx::aron::similarity::cosine::compute_similarity
double compute_similarity(const aron::data::NDArrayPtr p1, const aron::data::NDArrayPtr p2)
Definition: cosine.cpp:12
Logging.h
cosine.h