segment-graph.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 "segmentation/felzenszwalb/disjoint-set.h"
  20. // threshold function
  21. #define THRESHOLD(size, c) (c/size)
  22. namespace felzenszwalb{
  23. typedef struct {
  24. float w;
  25. int a, b;
  26. } edge;
  27. bool operator<(const edge &a, const edge &b) {
  28. return a.w < b.w;
  29. }
  30. /*
  31. * Segment a graph
  32. *
  33. * Returns a disjoint-set forest representing the segmentation.
  34. *
  35. * num_vertices: number of vertices in graph.
  36. * num_edges: number of edges in graph
  37. * edges: array of edges.
  38. * c: constant for treshold function.
  39. */
  40. universe *segment_graph(int num_vertices, int num_edges, edge *edges,
  41. float c) {
  42. // sort edges by weight
  43. std::sort(edges, edges + num_edges);
  44. // make a disjoint-set forest
  45. universe *u = new universe(num_vertices);
  46. // init thresholds
  47. float *threshold = new float[num_vertices];
  48. #pragma omp parallel for
  49. for (int i = 0; i < num_vertices; i++)
  50. threshold[i] = THRESHOLD(1,c);
  51. // for each edge, in non-decreasing weight order...
  52. for (int i = 0; i < num_edges; i++) {
  53. edge *pedge = &edges[i];
  54. // components conected by this edge
  55. int a = u->find(pedge->a);
  56. int b = u->find(pedge->b);
  57. if (a != b) {
  58. if ((pedge->w <= threshold[a]) &&
  59. (pedge->w <= threshold[b])) {
  60. u->join(a, b);
  61. a = u->find(a);
  62. threshold[a] = pedge->w + THRESHOLD(u->size(a), c);
  63. }
  64. }
  65. }
  66. // free up
  67. delete threshold;
  68. return u;
  69. }
  70. }//namespace
  71. #endif