1 | /* |
---|
2 | Copyright (C) 2006 Pedro Felzenszwalb |
---|
3 | |
---|
4 | This program is free software; you can redistribute it and/or modify |
---|
5 | it under the terms of the GNU General Public License as published by |
---|
6 | the Free Software Foundation; either version 2 of the License, or |
---|
7 | (at your option) any later version. |
---|
8 | |
---|
9 | This program is distributed in the hope that it will be useful, |
---|
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
12 | GNU General Public License for more details. |
---|
13 | |
---|
14 | You should have received a copy of the GNU General Public License |
---|
15 | along with this program; if not, write to the Free Software |
---|
16 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
---|
17 | */ |
---|
18 | |
---|
19 | #ifndef SEGMENT_GRAPH |
---|
20 | #define SEGMENT_GRAPH |
---|
21 | |
---|
22 | #include <algorithm> |
---|
23 | #include <cmath> |
---|
24 | #include "disjoint-set.h" |
---|
25 | |
---|
26 | // threshold function |
---|
27 | #define THRESHOLD(size, c) (c/size) |
---|
28 | |
---|
29 | typedef struct { |
---|
30 | float w; |
---|
31 | int a, b; |
---|
32 | } edge; |
---|
33 | |
---|
34 | bool operator<(const edge &a, const edge &b) { |
---|
35 | return a.w < b.w; |
---|
36 | } |
---|
37 | |
---|
38 | /* |
---|
39 | * Segment a graph |
---|
40 | * |
---|
41 | * Returns a disjoint-set forest representing the segmentation. |
---|
42 | * |
---|
43 | * num_vertices: number of vertices in graph. |
---|
44 | * num_edges: number of edges in graph |
---|
45 | * edges: array of edges. |
---|
46 | * c: constant for treshold function. |
---|
47 | */ |
---|
48 | universe *segment_graph(int num_vertices, int num_edges, edge *edges, |
---|
49 | float c) { |
---|
50 | // sort edges by weight |
---|
51 | std::sort(edges, edges + num_edges); |
---|
52 | |
---|
53 | // make a disjoint-set forest |
---|
54 | universe *u = new universe(num_vertices); |
---|
55 | |
---|
56 | // init thresholds |
---|
57 | float *threshold = new float[num_vertices]; |
---|
58 | for (int i = 0; i < num_vertices; i++) |
---|
59 | threshold[i] = THRESHOLD(1,c); |
---|
60 | |
---|
61 | // for each edge, in non-decreasing weight order... |
---|
62 | for (int i = 0; i < num_edges; i++) { |
---|
63 | edge *pedge = &edges[i]; |
---|
64 | |
---|
65 | // components conected by this edge |
---|
66 | int a = u->find(pedge->a); |
---|
67 | int b = u->find(pedge->b); |
---|
68 | if (a != b) { |
---|
69 | if ((pedge->w <= threshold[a]) && |
---|
70 | (pedge->w <= threshold[b])) { |
---|
71 | u->join(a, b); |
---|
72 | a = u->find(a); |
---|
73 | threshold[a] = pedge->w + THRESHOLD(u->size(a), c); |
---|
74 | } |
---|
75 | } |
---|
76 | } |
---|
77 | |
---|
78 | // free up |
---|
79 | delete threshold; |
---|
80 | return u; |
---|
81 | } |
---|
82 | |
---|
83 | #endif |
---|