add jaccardDistance measure for rectangle overlap
authorPavel Rojtberg <pavel.rojtberg@igd.fraunhofer.de>
Wed, 23 Dec 2015 12:06:56 +0000 (13:06 +0100)
committerPavel Rojtberg <pavel.rojtberg@igd.fraunhofer.de>
Wed, 23 Dec 2015 12:12:45 +0000 (13:12 +0100)
computes the complement of the Jaccard Index as described in
https://en.wikipedia.org/wiki/Jaccard_index. For rectangles this reduces
to computing the intersection over the union.

modules/core/include/opencv2/core/types.hpp

index e166556..6909676 100644 (file)
@@ -51,6 +51,7 @@
 #include <climits>
 #include <cfloat>
 #include <vector>
+#include <limits>
 
 #include "opencv2/core/cvdef.h"
 #include "opencv2/core/cvstd.hpp"
@@ -1832,7 +1833,26 @@ Rect_<_Tp> operator | (const Rect_<_Tp>& a, const Rect_<_Tp>& b)
     return c |= b;
 }
 
+/**
+ * @brief measure dissimilarity between two sample sets
+ *
+ * computes the complement of the Jaccard Index as described in <https://en.wikipedia.org/wiki/Jaccard_index>.
+ * For rectangles this reduces to computing the intersection over the union.
+ */
+template<typename _Tp> static inline
+double jaccardDistance(const Rect_<_Tp>& a, const Rect_<_Tp>& b) {
+    _Tp Aa = a.area();
+    _Tp Ab = b.area();
 
+    if ((Aa + Ab) <= std::numeric_limits<_Tp>::epsilon()) {
+        // jaccard_index = 1 -> distance = 0
+        return 0.0;
+    }
+
+    double Aab = (a & b).area();
+    // distance = 1 - jaccard_index
+    return 1.0 - Aab / (Aa + Ab - Aab);
+}
 
 ////////////////////////////// RotatedRect //////////////////////////////