File size: 2,421 Bytes
be94e5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html

#include "precomp.hpp"
#include "contours_common.hpp"
#include <map>
#include <limits>

using namespace std;
using namespace cv;

void cv::contourTreeToResults(CTree& tree,

                              int res_type,

                              OutputArrayOfArrays& _contours,

                              OutputArray& _hierarchy)

{
    // check if there are no results
    if (tree.isEmpty() || (tree.elem(0).body.isEmpty() && (tree.elem(0).first_child == -1)))
    {
        _contours.clear();
        return;
    }

    // mapping for indexes (original -> resulting)
    map<int, int> index_mapping;
    index_mapping[-1] = -1;
    index_mapping[0] = -1;

    CV_Assert(tree.size() < (size_t)numeric_limits<int>::max());
    const int total = (int)tree.size() - 1;
    _contours.create(total, 1, 0, -1, true);
    {
        int i = 0;
        CIterator it(tree);
        while (!it.isDone())
        {
            const CNode& elem = it.getNext_s();
            CV_Assert(elem.self() != -1);
            if (elem.self() == 0)
                continue;
            index_mapping[elem.self()] = i;
            CV_Assert(elem.body.size() < (size_t)numeric_limits<int>::max());
            const int sz = (int)elem.body.size();
            _contours.create(sz, 1, res_type, i, true);
            if (sz > 0)
            {
                Mat cmat = _contours.getMat(i);
                CV_Assert(cmat.isContinuous());
                elem.body.copyTo(cmat.data);
            }
            ++i;
        }
    }

    if (_hierarchy.needed())
    {
        _hierarchy.create(1, total, CV_32SC4, -1, true);
        Mat h_mat = _hierarchy.getMat();
        int i = 0;
        CIterator it(tree);
        while (!it.isDone())
        {
            const CNode& elem = it.getNext_s();
            if (elem.self() == 0)
                continue;
            Vec4i& h_vec = h_mat.at<Vec4i>(i);
            h_vec = Vec4i(index_mapping.at(elem.next),
                          index_mapping.at(elem.prev),
                          index_mapping.at(elem.first_child),
                          index_mapping.at(elem.parent));
            ++i;
        }
    }
}