template <typename Tp, int cn> KDTree <Tp, cn>:: KDTree(const cv::Mat &img, const int _leafNumber, const int _zeroThresh) : height(img.rows), width(img.cols), leafNumber(_leafNumber), zeroThresh(_zeroThresh) /////////////////////////////////////////////////// { int imgch = img.channels(); CV_Assert( img.isContinuous() && imgch <= cn); for(size_t i = 0; i < img.total(); i++) { cv::Vec<Tp, cn> v = cv::Vec<Tp, cn>::all((Tp)0); for (int c = 0; c < imgch; c++) { v[c] = *((Tp*)(img.data) + i*imgch + c); } data.push_back(v); } generate_seq( std::back_inserter(idx), 0, int(data.size()) ); std::fill_n( std::back_inserter(nodes), int(data.size()), cv::Point2i(0, 0) ); std::stack <int> left, right; left.push( 0 ); right.push( int(idx.size()) ); while ( !left.empty() ) { int _left = left.top(); left.pop(); int _right = right.top(); right.pop(); if ( _right - _left <= leafNumber) { for (int i = _left; i < _right; ++i) nodes[idx[i]] = cv::Point2i(_left, _right); continue; } int nth = _left + (_right - _left)/2; int dimIdx = getMaxSpreadN(_left, _right); KDTreeComparator comp( this, dimIdx ); std::nth_element(/**/ idx.begin() + _left, idx.begin() + nth, idx.begin() + _right, comp /**/); left.push(_left); right.push(nth + 1); left.push(nth + 1); right.push(_right); } }
template <typename Tp, int cn> KDTree <Tp, cn>:: KDTree(const cv::Mat &img, const int _leafNumber, const int _zeroThresh) : height(img.rows), width(img.cols), leafNumber(_leafNumber), zeroThresh(_zeroThresh) /////////////////////////////////////////////////// { CV_Assert( img.isContinuous() ); std::copy( (cv::Vec <Tp, cn> *) img.data, (cv::Vec <Tp, cn> *) img.data + img.total(), std::back_inserter(data) ); generate_seq( std::back_inserter(idx), 0, int(data.size()) ); std::fill_n( std::back_inserter(nodes), int(data.size()), cv::Point2i(0, 0) ); std::stack <int> left, right; left.push( 0 ); right.push( int(idx.size()) ); while ( !left.empty() ) { int _left = left.top(); left.pop(); int _right = right.top(); right.pop(); if ( _right - _left <= leafNumber) { for (int i = _left; i < _right; ++i) nodes[idx[i]] = cv::Point2i(_left, _right); continue; } int nth = _left + (_right - _left)/2; int dimIdx = getMaxSpreadN(_left, _right); KDTreeComparator comp( this, dimIdx ); std::nth_element(/**/ idx.begin() + _left, idx.begin() + nth, idx.begin() + _right, comp /**/); left.push(_left); right.push(nth + 1); left.push(nth + 1); right.push(_right); } }