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