cgv
Loading...
Searching...
No Matches
distance_transform.h
1#pragma once
2
3#include <cgv/math/vec.h>
4#include <cgv/math/mat.h>
5#include <cgv/math/functions.h>
6#include <limits>
7
8namespace cgv{
9 namespace math{
10
19template <typename T>
20void sqrdist_transf_1d(const vec<T>& f, vec<T>& d)
21{
22 static T INF =std::numeric_limits<T>::max();
23 unsigned n = f.size();
24 d.resize(n);
25 int *v = new int[n];
26 T *z = new T[n+1];
27 int k = 0;
28 v[0] = 0;
29 z[0] = -INF;
30 z[1] = +INF;
31
32 for (unsigned q = 1; q <= n-1; q++)
33 {
34 T s = ((f[q]+sqr(q))-(f[v[k]]+sqr(v[k])))/(2*q-2*v[k]);
35 while (s <= z[k])
36 {
37 k--;
38 s = ((f[q]+sqr(q))-(f[v[k]]+sqr(v[k])))/(2*q-2*v[k]);
39 }
40 k++;
41 v[k] = q;
42 z[k] = s;
43 z[k+1] = +INF;
44 }
45 k = 0;
46 for (unsigned q = 0; q <= n-1; q++)
47 {
48 while (z[k+1] < q)
49 k++;
50 d[q] = sqr(q-v[k]) + f[v[k]];
51 }
52
53 delete [] v;
54 delete [] z;
55}
56
57
58
59template <typename T>
60void sqrdist_transf_2d(mat<T> &im)
61{
62 static T INF =std::numeric_limits<T>::max();
63 unsigned width = im.ncols();
64 unsigned height = im.nrows();
65
66 vec<T> d;
67
68 // transform along columns
69 for (unsigned x = 0; x < width; x++)
70 {
71 sqrdist_transf_1d<T>(im.col(x), d);
72 im.set_col(x, d);
73 }
74
75 // transform along rows
76 for (unsigned y = 0; y < height; y++)
77 {
78 sqrdist_transf_1d<T>(im.row(y), d);
79 im.set_row(y, d);
80 }
81
82}
83
85template <typename T>
86void sqrdist_transf_2d(const mat<T>& input,mat<T>& output,T on = 1)
87{
88 static T INF =std::numeric_limits<T>::max();
89 unsigned width = input.nrows();
90 unsigned height = input.ncols();
91 output.resize(width,height);
92
93 for (unsigned y = 0; y < height; y++)
94 {
95 for (unsigned x = 0; x < width; x++)
96 {
97 if (input(x,y) == on)
98 output(x,y) = 0;
99 else
100 output(x,y) = INF;
101 }
102 }
103
104
105 sqrdist_transf_2d<T>(output);
106
107}
108
110template <typename T>
111void dist_transf_2d(mat<T>& input, mat<T>& output,T on = 1)
112{
113 sqrdist_transf_2d(input,output,on );
114 for(unsigned y = 0; y < output.ncols();y++)
115 {
116 for(unsigned x = 0; x < output.nrows();x++)
117 {
118 output(x,y)=sqrt(output(x,y));
119 }
120
121 }
122
123}
124
125 }
126}
the cgv namespace
Definition print.h:11