segment-graph.h 2.1 KB

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