operations.hpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. /*M///////////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
  4. //
  5. // By downloading, copying, installing or using the software you agree to this license.
  6. // If you do not agree to this license, do not download, install,
  7. // copy or use the software.
  8. //
  9. //
  10. // License Agreement
  11. // For Open Source Computer Vision Library
  12. //
  13. // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
  14. // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
  15. // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
  16. // Copyright (C) 2015, Itseez Inc., all rights reserved.
  17. // Third party copyrights are property of their respective owners.
  18. //
  19. // Redistribution and use in source and binary forms, with or without modification,
  20. // are permitted provided that the following conditions are met:
  21. //
  22. // * Redistribution's of source code must retain the above copyright notice,
  23. // this list of conditions and the following disclaimer.
  24. //
  25. // * Redistribution's in binary form must reproduce the above copyright notice,
  26. // this list of conditions and the following disclaimer in the documentation
  27. // and/or other materials provided with the distribution.
  28. //
  29. // * The name of the copyright holders may not be used to endorse or promote products
  30. // derived from this software without specific prior written permission.
  31. //
  32. // This software is provided by the copyright holders and contributors "as is" and
  33. // any express or implied warranties, including, but not limited to, the implied
  34. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  35. // In no event shall the Intel Corporation or contributors be liable for any direct,
  36. // indirect, incidental, special, exemplary, or consequential damages
  37. // (including, but not limited to, procurement of substitute goods or services;
  38. // loss of use, data, or profits; or business interruption) however caused
  39. // and on any theory of liability, whether in contract, strict liability,
  40. // or tort (including negligence or otherwise) arising in any way out of
  41. // the use of this software, even if advised of the possibility of such damage.
  42. //
  43. //M*/
  44. #ifndef OPENCV_CORE_OPERATIONS_HPP
  45. #define OPENCV_CORE_OPERATIONS_HPP
  46. #ifndef __cplusplus
  47. # error operations.hpp header must be compiled as C++
  48. #endif
  49. #include <cstdio>
  50. //! @cond IGNORED
  51. namespace cv
  52. {
  53. ////////////////////////////// Matx methods depending on core API /////////////////////////////
  54. namespace internal
  55. {
  56. template<typename _Tp, int m> struct Matx_FastInvOp
  57. {
  58. bool operator()(const Matx<_Tp, m, m>& a, Matx<_Tp, m, m>& b, int method) const
  59. {
  60. Matx<_Tp, m, m> temp = a;
  61. // assume that b is all 0's on input => make it a unity matrix
  62. for( int i = 0; i < m; i++ )
  63. b(i, i) = (_Tp)1;
  64. if( method == DECOMP_CHOLESKY )
  65. return Cholesky(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m);
  66. return LU(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m) != 0;
  67. }
  68. };
  69. template<typename _Tp> struct Matx_FastInvOp<_Tp, 2>
  70. {
  71. bool operator()(const Matx<_Tp, 2, 2>& a, Matx<_Tp, 2, 2>& b, int) const
  72. {
  73. _Tp d = (_Tp)determinant(a);
  74. if( d == 0 )
  75. return false;
  76. d = 1/d;
  77. b(1,1) = a(0,0)*d;
  78. b(0,0) = a(1,1)*d;
  79. b(0,1) = -a(0,1)*d;
  80. b(1,0) = -a(1,0)*d;
  81. return true;
  82. }
  83. };
  84. template<typename _Tp> struct Matx_FastInvOp<_Tp, 3>
  85. {
  86. bool operator()(const Matx<_Tp, 3, 3>& a, Matx<_Tp, 3, 3>& b, int) const
  87. {
  88. _Tp d = (_Tp)determinant(a);
  89. if( d == 0 )
  90. return false;
  91. d = 1/d;
  92. b(0,0) = (a(1,1) * a(2,2) - a(1,2) * a(2,1)) * d;
  93. b(0,1) = (a(0,2) * a(2,1) - a(0,1) * a(2,2)) * d;
  94. b(0,2) = (a(0,1) * a(1,2) - a(0,2) * a(1,1)) * d;
  95. b(1,0) = (a(1,2) * a(2,0) - a(1,0) * a(2,2)) * d;
  96. b(1,1) = (a(0,0) * a(2,2) - a(0,2) * a(2,0)) * d;
  97. b(1,2) = (a(0,2) * a(1,0) - a(0,0) * a(1,2)) * d;
  98. b(2,0) = (a(1,0) * a(2,1) - a(1,1) * a(2,0)) * d;
  99. b(2,1) = (a(0,1) * a(2,0) - a(0,0) * a(2,1)) * d;
  100. b(2,2) = (a(0,0) * a(1,1) - a(0,1) * a(1,0)) * d;
  101. return true;
  102. }
  103. };
  104. template<typename _Tp, int m, int n> struct Matx_FastSolveOp
  105. {
  106. bool operator()(const Matx<_Tp, m, m>& a, const Matx<_Tp, m, n>& b,
  107. Matx<_Tp, m, n>& x, int method) const
  108. {
  109. Matx<_Tp, m, m> temp = a;
  110. x = b;
  111. if( method == DECOMP_CHOLESKY )
  112. return Cholesky(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n);
  113. return LU(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n) != 0;
  114. }
  115. };
  116. template<typename _Tp> struct Matx_FastSolveOp<_Tp, 2, 1>
  117. {
  118. bool operator()(const Matx<_Tp, 2, 2>& a, const Matx<_Tp, 2, 1>& b,
  119. Matx<_Tp, 2, 1>& x, int) const
  120. {
  121. _Tp d = (_Tp)determinant(a);
  122. if( d == 0 )
  123. return false;
  124. d = 1/d;
  125. x(0) = (b(0)*a(1,1) - b(1)*a(0,1))*d;
  126. x(1) = (b(1)*a(0,0) - b(0)*a(1,0))*d;
  127. return true;
  128. }
  129. };
  130. template<typename _Tp> struct Matx_FastSolveOp<_Tp, 3, 1>
  131. {
  132. bool operator()(const Matx<_Tp, 3, 3>& a, const Matx<_Tp, 3, 1>& b,
  133. Matx<_Tp, 3, 1>& x, int) const
  134. {
  135. _Tp d = (_Tp)determinant(a);
  136. if( d == 0 )
  137. return false;
  138. d = 1/d;
  139. x(0) = d*(b(0)*(a(1,1)*a(2,2) - a(1,2)*a(2,1)) -
  140. a(0,1)*(b(1)*a(2,2) - a(1,2)*b(2)) +
  141. a(0,2)*(b(1)*a(2,1) - a(1,1)*b(2)));
  142. x(1) = d*(a(0,0)*(b(1)*a(2,2) - a(1,2)*b(2)) -
  143. b(0)*(a(1,0)*a(2,2) - a(1,2)*a(2,0)) +
  144. a(0,2)*(a(1,0)*b(2) - b(1)*a(2,0)));
  145. x(2) = d*(a(0,0)*(a(1,1)*b(2) - b(1)*a(2,1)) -
  146. a(0,1)*(a(1,0)*b(2) - b(1)*a(2,0)) +
  147. b(0)*(a(1,0)*a(2,1) - a(1,1)*a(2,0)));
  148. return true;
  149. }
  150. };
  151. } // internal
  152. template<typename _Tp, int m, int n> inline
  153. Matx<_Tp,m,n> Matx<_Tp,m,n>::randu(_Tp a, _Tp b)
  154. {
  155. Matx<_Tp,m,n> M;
  156. cv::randu(M, Scalar(a), Scalar(b));
  157. return M;
  158. }
  159. template<typename _Tp, int m, int n> inline
  160. Matx<_Tp,m,n> Matx<_Tp,m,n>::randn(_Tp a, _Tp b)
  161. {
  162. Matx<_Tp,m,n> M;
  163. cv::randn(M, Scalar(a), Scalar(b));
  164. return M;
  165. }
  166. template<typename _Tp, int m, int n> inline
  167. Matx<_Tp, n, m> Matx<_Tp, m, n>::inv(int method, bool *p_is_ok /*= NULL*/) const
  168. {
  169. Matx<_Tp, n, m> b;
  170. bool ok;
  171. if( method == DECOMP_LU || method == DECOMP_CHOLESKY )
  172. ok = cv::internal::Matx_FastInvOp<_Tp, m>()(*this, b, method);
  173. else
  174. {
  175. Mat A(*this, false), B(b, false);
  176. ok = (invert(A, B, method) != 0);
  177. }
  178. if( NULL != p_is_ok ) { *p_is_ok = ok; }
  179. return ok ? b : Matx<_Tp, n, m>::zeros();
  180. }
  181. template<typename _Tp, int m, int n> template<int l> inline
  182. Matx<_Tp, n, l> Matx<_Tp, m, n>::solve(const Matx<_Tp, m, l>& rhs, int method) const
  183. {
  184. Matx<_Tp, n, l> x;
  185. bool ok;
  186. if( method == DECOMP_LU || method == DECOMP_CHOLESKY )
  187. ok = cv::internal::Matx_FastSolveOp<_Tp, m, l>()(*this, rhs, x, method);
  188. else
  189. {
  190. Mat A(*this, false), B(rhs, false), X(x, false);
  191. ok = cv::solve(A, B, X, method);
  192. }
  193. return ok ? x : Matx<_Tp, n, l>::zeros();
  194. }
  195. ////////////////////////// Augmenting algebraic & logical operations //////////////////////////
  196. #define CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \
  197. static inline A& operator op (A& a, const B& b) { cvop; return a; }
  198. #define CV_MAT_AUG_OPERATOR(op, cvop, A, B) \
  199. CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \
  200. CV_MAT_AUG_OPERATOR1(op, cvop, const A, B)
  201. #define CV_MAT_AUG_OPERATOR_T(op, cvop, A, B) \
  202. template<typename _Tp> CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \
  203. template<typename _Tp> CV_MAT_AUG_OPERATOR1(op, cvop, const A, B)
  204. CV_MAT_AUG_OPERATOR (+=, cv::add(a,b,a), Mat, Mat)
  205. CV_MAT_AUG_OPERATOR (+=, cv::add(a,b,a), Mat, Scalar)
  206. CV_MAT_AUG_OPERATOR_T(+=, cv::add(a,b,a), Mat_<_Tp>, Mat)
  207. CV_MAT_AUG_OPERATOR_T(+=, cv::add(a,b,a), Mat_<_Tp>, Scalar)
  208. CV_MAT_AUG_OPERATOR_T(+=, cv::add(a,b,a), Mat_<_Tp>, Mat_<_Tp>)
  209. CV_MAT_AUG_OPERATOR (-=, cv::subtract(a,b,a), Mat, Mat)
  210. CV_MAT_AUG_OPERATOR (-=, cv::subtract(a,b,a), Mat, Scalar)
  211. CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a,b,a), Mat_<_Tp>, Mat)
  212. CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a,b,a), Mat_<_Tp>, Scalar)
  213. CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a,b,a), Mat_<_Tp>, Mat_<_Tp>)
  214. CV_MAT_AUG_OPERATOR (*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat, Mat)
  215. CV_MAT_AUG_OPERATOR_T(*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat_<_Tp>, Mat)
  216. CV_MAT_AUG_OPERATOR_T(*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat_<_Tp>, Mat_<_Tp>)
  217. CV_MAT_AUG_OPERATOR (*=, a.convertTo(a, -1, b), Mat, double)
  218. CV_MAT_AUG_OPERATOR_T(*=, a.convertTo(a, -1, b), Mat_<_Tp>, double)
  219. CV_MAT_AUG_OPERATOR (/=, cv::divide(a,b,a), Mat, Mat)
  220. CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a,b,a), Mat_<_Tp>, Mat)
  221. CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a,b,a), Mat_<_Tp>, Mat_<_Tp>)
  222. CV_MAT_AUG_OPERATOR (/=, a.convertTo((Mat&)a, -1, 1./b), Mat, double)
  223. CV_MAT_AUG_OPERATOR_T(/=, a.convertTo((Mat&)a, -1, 1./b), Mat_<_Tp>, double)
  224. CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a,b,a), Mat, Mat)
  225. CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a,b,a), Mat, Scalar)
  226. CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a,b,a), Mat_<_Tp>, Mat)
  227. CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a,b,a), Mat_<_Tp>, Scalar)
  228. CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a,b,a), Mat_<_Tp>, Mat_<_Tp>)
  229. CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a,b,a), Mat, Mat)
  230. CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a,b,a), Mat, Scalar)
  231. CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a,b,a), Mat_<_Tp>, Mat)
  232. CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a,b,a), Mat_<_Tp>, Scalar)
  233. CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a,b,a), Mat_<_Tp>, Mat_<_Tp>)
  234. CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a,b,a), Mat, Mat)
  235. CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a,b,a), Mat, Scalar)
  236. CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a,b,a), Mat_<_Tp>, Mat)
  237. CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a,b,a), Mat_<_Tp>, Scalar)
  238. CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a,b,a), Mat_<_Tp>, Mat_<_Tp>)
  239. #undef CV_MAT_AUG_OPERATOR_T
  240. #undef CV_MAT_AUG_OPERATOR
  241. #undef CV_MAT_AUG_OPERATOR1
  242. ///////////////////////////////////////////// SVD /////////////////////////////////////////////
  243. inline SVD::SVD() {}
  244. inline SVD::SVD( InputArray m, int flags ) { operator ()(m, flags); }
  245. inline void SVD::solveZ( InputArray m, OutputArray _dst )
  246. {
  247. Mat mtx = m.getMat();
  248. SVD svd(mtx, (mtx.rows >= mtx.cols ? 0 : SVD::FULL_UV));
  249. _dst.create(svd.vt.cols, 1, svd.vt.type());
  250. Mat dst = _dst.getMat();
  251. svd.vt.row(svd.vt.rows-1).reshape(1,svd.vt.cols).copyTo(dst);
  252. }
  253. template<typename _Tp, int m, int n, int nm> inline void
  254. SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt )
  255. {
  256. CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector.");
  257. Mat _a(a, false), _u(u, false), _w(w, false), _vt(vt, false);
  258. SVD::compute(_a, _w, _u, _vt);
  259. CV_Assert(_w.data == (uchar*)&w.val[0] && _u.data == (uchar*)&u.val[0] && _vt.data == (uchar*)&vt.val[0]);
  260. }
  261. template<typename _Tp, int m, int n, int nm> inline void
  262. SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w )
  263. {
  264. CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector.");
  265. Mat _a(a, false), _w(w, false);
  266. SVD::compute(_a, _w);
  267. CV_Assert(_w.data == (uchar*)&w.val[0]);
  268. }
  269. template<typename _Tp, int m, int n, int nm, int nb> inline void
  270. SVD::backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u,
  271. const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs,
  272. Matx<_Tp, n, nb>& dst )
  273. {
  274. CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector.");
  275. Mat _u(u, false), _w(w, false), _vt(vt, false), _rhs(rhs, false), _dst(dst, false);
  276. SVD::backSubst(_w, _u, _vt, _rhs, _dst);
  277. CV_Assert(_dst.data == (uchar*)&dst.val[0]);
  278. }
  279. /////////////////////////////////// Multiply-with-Carry RNG ///////////////////////////////////
  280. inline RNG::RNG() { state = 0xffffffff; }
  281. inline RNG::RNG(uint64 _state) { state = _state ? _state : 0xffffffff; }
  282. inline RNG::operator uchar() { return (uchar)next(); }
  283. inline RNG::operator schar() { return (schar)next(); }
  284. inline RNG::operator ushort() { return (ushort)next(); }
  285. inline RNG::operator short() { return (short)next(); }
  286. inline RNG::operator int() { return (int)next(); }
  287. inline RNG::operator unsigned() { return next(); }
  288. inline RNG::operator float() { return next()*2.3283064365386962890625e-10f; }
  289. inline RNG::operator double() { unsigned t = next(); return (((uint64)t << 32) | next()) * 5.4210108624275221700372640043497e-20; }
  290. inline unsigned RNG::operator ()(unsigned N) { return (unsigned)uniform(0,N); }
  291. inline unsigned RNG::operator ()() { return next(); }
  292. inline int RNG::uniform(int a, int b) { return a == b ? a : (int)(next() % (b - a) + a); }
  293. inline float RNG::uniform(float a, float b) { return ((float)*this)*(b - a) + a; }
  294. inline double RNG::uniform(double a, double b) { return ((double)*this)*(b - a) + a; }
  295. inline bool RNG::operator ==(const RNG& other) const { return state == other.state; }
  296. inline unsigned RNG::next()
  297. {
  298. state = (uint64)(unsigned)state* /*CV_RNG_COEFF*/ 4164903690U + (unsigned)(state >> 32);
  299. return (unsigned)state;
  300. }
  301. //! returns the next unifomly-distributed random number of the specified type
  302. template<typename _Tp> static inline _Tp randu()
  303. {
  304. return (_Tp)theRNG();
  305. }
  306. ///////////////////////////////// Formatted string generation /////////////////////////////////
  307. CV_EXPORTS String format( const char* fmt, ... );
  308. ///////////////////////////////// Formatted output of cv::Mat /////////////////////////////////
  309. static inline
  310. Ptr<Formatted> format(InputArray mtx, int fmt)
  311. {
  312. return Formatter::get(fmt)->format(mtx.getMat());
  313. }
  314. static inline
  315. int print(Ptr<Formatted> fmtd, FILE* stream = stdout)
  316. {
  317. int written = 0;
  318. fmtd->reset();
  319. for(const char* str = fmtd->next(); str; str = fmtd->next())
  320. written += fputs(str, stream);
  321. return written;
  322. }
  323. static inline
  324. int print(const Mat& mtx, FILE* stream = stdout)
  325. {
  326. return print(Formatter::get()->format(mtx), stream);
  327. }
  328. static inline
  329. int print(const UMat& mtx, FILE* stream = stdout)
  330. {
  331. return print(Formatter::get()->format(mtx.getMat(ACCESS_READ)), stream);
  332. }
  333. template<typename _Tp> static inline
  334. int print(const std::vector<Point_<_Tp> >& vec, FILE* stream = stdout)
  335. {
  336. return print(Formatter::get()->format(Mat(vec)), stream);
  337. }
  338. template<typename _Tp> static inline
  339. int print(const std::vector<Point3_<_Tp> >& vec, FILE* stream = stdout)
  340. {
  341. return print(Formatter::get()->format(Mat(vec)), stream);
  342. }
  343. template<typename _Tp, int m, int n> static inline
  344. int print(const Matx<_Tp, m, n>& matx, FILE* stream = stdout)
  345. {
  346. return print(Formatter::get()->format(cv::Mat(matx)), stream);
  347. }
  348. //! @endcond
  349. /****************************************************************************************\
  350. * Auxiliary algorithms *
  351. \****************************************************************************************/
  352. /** @brief Splits an element set into equivalency classes.
  353. The generic function partition implements an \f$O(N^2)\f$ algorithm for splitting a set of \f$N\f$ elements
  354. into one or more equivalency classes, as described in
  355. <http://en.wikipedia.org/wiki/Disjoint-set_data_structure> . The function returns the number of
  356. equivalency classes.
  357. @param _vec Set of elements stored as a vector.
  358. @param labels Output vector of labels. It contains as many elements as vec. Each label labels[i] is
  359. a 0-based cluster index of `vec[i]`.
  360. @param predicate Equivalence predicate (pointer to a boolean function of two arguments or an
  361. instance of the class that has the method bool operator()(const _Tp& a, const _Tp& b) ). The
  362. predicate returns true when the elements are certainly in the same class, and returns false if they
  363. may or may not be in the same class.
  364. @ingroup core_cluster
  365. */
  366. template<typename _Tp, class _EqPredicate> int
  367. partition( const std::vector<_Tp>& _vec, std::vector<int>& labels,
  368. _EqPredicate predicate=_EqPredicate())
  369. {
  370. int i, j, N = (int)_vec.size();
  371. const _Tp* vec = &_vec[0];
  372. const int PARENT=0;
  373. const int RANK=1;
  374. std::vector<int> _nodes(N*2);
  375. int (*nodes)[2] = (int(*)[2])&_nodes[0];
  376. // The first O(N) pass: create N single-vertex trees
  377. for(i = 0; i < N; i++)
  378. {
  379. nodes[i][PARENT]=-1;
  380. nodes[i][RANK] = 0;
  381. }
  382. // The main O(N^2) pass: merge connected components
  383. for( i = 0; i < N; i++ )
  384. {
  385. int root = i;
  386. // find root
  387. while( nodes[root][PARENT] >= 0 )
  388. root = nodes[root][PARENT];
  389. for( j = 0; j < N; j++ )
  390. {
  391. if( i == j || !predicate(vec[i], vec[j]))
  392. continue;
  393. int root2 = j;
  394. while( nodes[root2][PARENT] >= 0 )
  395. root2 = nodes[root2][PARENT];
  396. if( root2 != root )
  397. {
  398. // unite both trees
  399. int rank = nodes[root][RANK], rank2 = nodes[root2][RANK];
  400. if( rank > rank2 )
  401. nodes[root2][PARENT] = root;
  402. else
  403. {
  404. nodes[root][PARENT] = root2;
  405. nodes[root2][RANK] += rank == rank2;
  406. root = root2;
  407. }
  408. CV_Assert( nodes[root][PARENT] < 0 );
  409. int k = j, parent;
  410. // compress the path from node2 to root
  411. while( (parent = nodes[k][PARENT]) >= 0 )
  412. {
  413. nodes[k][PARENT] = root;
  414. k = parent;
  415. }
  416. // compress the path from node to root
  417. k = i;
  418. while( (parent = nodes[k][PARENT]) >= 0 )
  419. {
  420. nodes[k][PARENT] = root;
  421. k = parent;
  422. }
  423. }
  424. }
  425. }
  426. // Final O(N) pass: enumerate classes
  427. labels.resize(N);
  428. int nclasses = 0;
  429. for( i = 0; i < N; i++ )
  430. {
  431. int root = i;
  432. while( nodes[root][PARENT] >= 0 )
  433. root = nodes[root][PARENT];
  434. // re-use the rank as the class label
  435. if( nodes[root][RANK] >= 0 )
  436. nodes[root][RANK] = ~nclasses++;
  437. labels[i] = ~nodes[root][RANK];
  438. }
  439. return nclasses;
  440. }
  441. } // cv
  442. #endif