Img2Num C++ (Internal Developer Docs) dev
API Documentation
Loading...
Searching...
No Matches
graph.cpp
1#include "internal/graph.h"
2
3#include "internal/bezier.h"
4#include "internal/douglas_peucker.h"
5#include "internal/Pixel.h"
6#include "internal/shared_contours.h"
7
8#include <algorithm>
9#include <cmath>
10#include <cstdlib>
11#include <iterator>
12#include <queue>
13#include <string>
14/*
15 Graph class - manages Node class
16*/
17
18static inline float
19colorDistance(const ImageLib::RGBPixel<uint8_t>& a, const ImageLib::RGBPixel<uint8_t>& b) {
21 static_cast<float>(a.red), static_cast<float>(a.green), static_cast<float>(a.blue)
22 };
24 static_cast<float>(b.red), static_cast<float>(b.green), static_cast<float>(b.blue)
25 };
26 return std::sqrt(
27 (af.red - bf.red) * (af.red - bf.red) + (af.green - bf.green) * (af.green - bf.green) +
28 (af.blue - bf.blue) * (af.blue - bf.blue)
29 );
30}
31
32/*
33To quickly search m_nodes (std::vector) for the index of a node id
34create an std::unordered_map of node id - index pairs
35indexing time of std::vector by value is O(N)
36lookup time of std::unordered_map by key is O(log(N))
37*/
38void Graph::hash_node_ids() {
39 for (int32_t i {0}; i < m_nodes->size(); i++) {
40 const int32_t key {m_nodes->at(i)->id()};
41 m_node_ids[key] = i;
42 }
43}
44
45bool Graph::all_areas_bigger_than(int32_t min_area) {
46 for (auto& n : *m_nodes) {
47 if (n->area() < min_area) {
48 return false;
49 }
50 }
51
52 return true;
53}
54
55bool Graph::add_edge(int32_t node_id1, int32_t node_id2) {
56 auto end_node_ids {m_node_ids.end()};
57 auto node1_it {m_node_ids.find(node_id1)};
58 auto node2_it {m_node_ids.find(node_id2)};
59
60 if (node1_it == end_node_ids || node2_it == end_node_ids) {
61 return false;
62 }
63
64 const int32_t idx1 {node1_it->second};
65 const int32_t idx2 {node2_it->second};
66
67 m_nodes->at(idx1)->add_edge(m_nodes->at(idx2));
68 m_nodes->at(idx2)->add_edge(m_nodes->at(idx1));
69 return true;
70}
71
72bool Graph::merge_nodes(const Node_ptr& node_to_keep, const Node_ptr& node_to_remove) {
73 auto end_node_ids {m_node_ids.end()};
74 auto node1_it {m_node_ids.find(node_to_keep->id())};
75 auto node2_it {m_node_ids.find(node_to_remove->id())};
76
77 if (node1_it == end_node_ids || node2_it == end_node_ids) {
78 return false;
79 }
80
81 const int32_t idx_k {node1_it->second};
82 const int32_t idx_r {node2_it->second};
83
84 // transfer edges from node_to_remove to node_to_keep
85 for (Node_ptr n : m_nodes->at(idx_r)->edges()) {
86 if (n->id() != node_to_keep->id()) {
87 // prevents self referencing
88 n->remove_edge(node_to_remove);
89 n->add_edge(node_to_keep);
90 node_to_keep->add_edge(n);
91 }
92 }
93
94 node_to_keep->add_pixels(node_to_remove->get_pixels());
95
96 node_to_remove->clear_all();
97
98 return true;
99}
100
101void Graph::clear_unconnected_nodes() {
102 std::vector<Node_ptr>& nodes {*m_nodes};
103
104 nodes.erase(
105 std::remove_if(
106 nodes.begin(), nodes.end(), [](const Node_ptr& n) { return n->area() == 0; }
107 ),
108 nodes.end()
109 );
110
111 hash_node_ids();
112}
113
114void Graph::discover_edges(
115 const std::vector<int32_t>& region_labels, const int32_t width, const int32_t height
116) {
117 // Moore 8-connected neighbourhood
118 constexpr int8_t dirs[8][2] {{1, 0}, {-1, 0}, {0, 1}, {0, -1},
119 {1, 1}, {-1, -1}, {-1, 1}, {1, -1}};
120
121 int32_t rneigh[8];
122
123 for (int32_t y {0}; y < height; ++y) {
124 for (int32_t x {0}; x < width; ++x) {
125 const int32_t idx {y * width + x};
126 const int32_t rid {region_labels[idx]};
127
128 for (int32_t k {0}; k < 8; ++k) {
129 const int32_t nx {x + dirs[k][0]};
130 const int32_t ny {y + dirs[k][1]};
131
132 if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
133 rneigh[k] = region_labels[ny * width + nx];
134 } else {
135 rneigh[k] = rid; // ignore out-of-bounds
136 }
137 }
138
139 for (int32_t r : rneigh) {
140 if (r != rid) {
141 add_edge(rid, r);
142 }
143 }
144 }
145 }
146}
147
148void Graph::process_overlapping_edges() {
149 // 1. Build the Global Label Map ONCE (0 = background, else = node->id())
150 std::vector<int32_t> label_map(static_cast<size_t>(m_width) * static_cast<size_t>(m_height), 0);
151
152 for (const Node_ptr& n : get_nodes()) {
153 if (n->area() == 0)
154 continue;
155
156 for (auto& [_, p] : n->get_pixels()) {
157 label_map[p.y * m_width + p.x] = n->id();
158 }
159 }
160
161 constexpr int8_t dirs[8][2] {{1, 0}, {-1, 0}, {0, 1}, {0, -1},
162 {1, 1}, {-1, -1}, {-1, 1}, {1, -1}};
163
164 // 2. Iterate directly over the pixels of each node
165 for (const Node_ptr& n : get_nodes()) {
166 if (n->area() == 0)
167 continue;
168 int32_t val = n->id();
169
170 for (auto& [_, p] : n->get_pixels()) {
171 int x = p.x;
172 int y = p.y;
173
174 // Check 8 neighbors in the global map
175 for (int k = 0; k < 8; ++k) {
176 int nx = x + dirs[k][0];
177 int ny = y + dirs[k][1];
178
179 // Fast boundary check (replaces std::clamp)
180 if (nx < 0 || nx >= m_width || ny < 0 || ny >= m_height)
181 continue;
182
183 int32_t n_val = label_map[ny * m_width + nx];
184
185 // Is it a neighbor? AND have we not processed this pairing yet?
186 if (n_val != 0 && n_val != val && val < n_val) {
187 bool is_too_thin = false;
188
189 // Check around the neighbor pixel for a 3rd region (pinching)
190 for (int mk = 0; mk < 8; ++mk) {
191 int mx = nx + dirs[mk][0];
192 int my = ny + dirs[mk][1];
193
194 if (mx < 0 || mx >= m_width || my < 0 || my >= m_height)
195 continue;
196
197 int32_t m_val = label_map[my * m_width + mx];
198
199 if (m_val != 0 && m_val != val && m_val != n_val) {
200 is_too_thin = true;
201 break; // CRITICAL: Stop checking immediately once proven thin!
202 }
203 }
204
205 if (is_too_thin) {
206 // Give our pixel to the neighbor
207 Node_ptr neighbor_node =
208 m_nodes->at(m_node_ids[n_val]); // get_node_by_id(n_val); // Assuming
209 // you have this lookup
210 if (neighbor_node) {
211 neighbor_node->add_edge_pixel(XY {x, y});
212 }
213 } else {
214 // Take the neighbor's pixel
215 n->add_edge_pixel(XY {nx, ny});
216 }
217 }
218 }
219 }
220 }
221}
222
223std::vector<uint8_t> Graph::analyzeJunctions(const std::vector<uint8_t>& skel, int w, int h) {
224 std::vector<uint8_t> junction_map(static_cast<size_t>(w) * h, 0);
225
226 // 8-Neighbor Order (Clockwise)
227 // P9 P2 P3
228 // P8 P1 P4
229 // P7 P6 P5
230 int dx[] = {0, 1, 1, 1, 0, -1, -1, -1};
231 int dy[] = {-1, -1, 0, 1, 1, 1, 0, -1};
232
233 for (int y = 0; y < h; ++y) {
234 for (int x = 0; x < w; ++x) {
235 if (getPixel(skel, w, h, x, y) == 0)
236 continue;
237
238 // 1. Get Neighbors in Circular Order
239 int p[8];
240 for (int k = 0; k < 8; ++k) {
241 p[k] = getPixel(skel, w, h, x + dx[k], y + dy[k]) ? 1 : 0;
242 }
243
244 // 2. Count Transitions (0 -> 1)
245 // This is the Crossing Number / 2
246 int transitions = 0;
247 for (int k = 0; k < 8; ++k) {
248 if (p[k] == 0 && p[(k + 1) % 8] == 1)
249 transitions++;
250 }
251
252 // 3. Count Total Neighbors (for Endpoint check)
253 int neighbors = 0;
254 for (int k = 0; k < 8; ++k)
255 neighbors += p[k];
256
257 // 4. Classify
258 if (transitions >= 3) {
259 junction_map[y * w + x] = 1;
260 }
261 }
262 }
263 return junction_map;
264}
265
266void Graph::compute_contours() {
267
268 /*
269 Shared-edge mode: build region boundaries on the crack grid so
270 neighbouring contours are exactly coincident along shared edges -- no
271 overlap band, no gaps
272 */
273
274 float eps = 0.25f;
275
276 std::vector<int32_t> labels(static_cast<size_t>(m_width) * m_height, -1);
277 for (const Node_ptr& n : get_nodes()) {
278 if (n->area() == 0)
279 continue;
280 for (auto& p : n->get_pixels())
281 labels[static_cast<size_t>(p.position.y) * m_width + p.position.x] = n->id();
282 }
283
284 auto loops = build_shared_loops(labels, m_width, m_height, eps);
285
286 for (const Node_ptr& n : get_nodes()) {
287 if (n->area() == 0)
288 continue;
289 n->clear_contour();
290 auto it = loops.find(n->id());
291 if (it == loops.end())
292 continue;
293 ImageLib::RGBPixel<uint8_t> c = n->color();
294 ImageLib::RGBAPixel<uint8_t> col {c.red, c.green, c.blue, 255};
295 for (std::vector<QuadBezier>& curve : it->second) {
296 std::vector<Point> anchors; // keep contours[] parallel to curves[]
297 anchors.reserve(curve.size() + 1);
298 for (const QuadBezier& q : curve)
299 anchors.push_back(q.p0);
300 if (!curve.empty())
301 anchors.push_back(curve.back().p2);
302 n->m_contours.contours.push_back(std::move(anchors));
303 n->m_contours.curves.push_back(std::move(curve));
304 n->m_contours.colors.push_back(col);
305 n->m_contours.hierarchy.push_back({-1, -1, -1, -1});
306 n->m_contours.is_hole.push_back(false);
307 }
308 }
309}
310
311namespace {
312
313// 1D squared-distance transform (Felzenszwalb & Huttenlocher): for every q,
314// d[q] = min_p ( (q - p)^2 + f[p] ). O(n).
315void dt_1d(const std::vector<float>& f, std::vector<float>& d, int n) {
316 constexpr float INF = 1e20f;
317 std::vector<int> v(n);
318 std::vector<float> z(n + 1);
319 int k = 0;
320 v[0] = 0;
321 z[0] = -INF;
322 z[1] = INF;
323 for (int q = 1; q < n; ++q) {
324 float s;
325 while (true) {
326 s = ((f[q] + static_cast<float>(q) * q) - (f[v[k]] + static_cast<float>(v[k]) * v[k])) /
327 (2.0f * static_cast<float>(q - v[k]));
328 if (s <= z[k] && k > 0) {
329 --k;
330 } else {
331 break;
332 }
333 }
334 ++k;
335 v[k] = q;
336 z[k] = s;
337 z[k + 1] = INF;
338 }
339 k = 0;
340 for (int q = 0; q < n; ++q) {
341 while (z[k + 1] < static_cast<float>(q))
342 ++k;
343 const float dq = static_cast<float>(q - v[k]);
344 d[q] = dq * dq + f[v[k]];
345 }
346}
347
348// Largest inscribed-disk radius (in pixels) of a region: the maximum over all
349// region pixels of the Euclidean distance to the nearest non-region pixel.
350// Computed with an exact squared Euclidean distance transform, so the result is
351// independent of how long or how curved the region is -- a property that a
352// bounding-box aspect ratio does not have. Thickness ~= 2 * this radius.
353float max_inscribed_radius(const Node_ptr& n) {
354 std::vector<uint8_t> mask;
355 const std::array<int, 4> xywh = n->create_binary_image(mask); // tight bbox
356 const int w = xywh[2];
357 const int h = xywh[3];
358 if (w <= 0 || h <= 0)
359 return 0.0f;
360
361 // Pad by one pixel so the region's boundary against the exterior is treated
362 // as background by the distance transform.
363 const int pw = w + 2;
364 const int ph = h + 2;
365 constexpr float INF = 1e20f;
366
367 std::vector<float> grid(static_cast<size_t>(pw) * ph);
368 for (int y = 0; y < ph; ++y) {
369 for (int x = 0; x < pw; ++x) {
370 const bool inside = x >= 1 && x <= w && y >= 1 && y <= h &&
371 mask[static_cast<size_t>(y - 1) * w + (x - 1)];
372 grid[static_cast<size_t>(y) * pw + x] = inside ? INF : 0.0f;
373 }
374 }
375
376 // Separable two-pass transform: columns first, then rows.
377 std::vector<float> in, out(std::max(pw, ph));
378 in.resize(ph);
379 for (int x = 0; x < pw; ++x) {
380 for (int y = 0; y < ph; ++y)
381 in[y] = grid[static_cast<size_t>(y) * pw + x];
382 dt_1d(in, out, ph);
383 for (int y = 0; y < ph; ++y)
384 grid[static_cast<size_t>(y) * pw + x] = out[y];
385 }
386 in.resize(pw);
387 float max_d2 = 0.0f;
388 for (int y = 0; y < ph; ++y) {
389 for (int x = 0; x < pw; ++x)
390 in[x] = grid[static_cast<size_t>(y) * pw + x];
391 dt_1d(in, out, pw);
392 for (int x = 0; x < pw; ++x)
393 if (out[x] > max_d2)
394 max_d2 = out[x];
395 }
396 return std::sqrt(max_d2);
397}
398
399} // namespace
400
401void Graph::merge_small_area_nodes(const int32_t min_area, const int32_t min_thickness) {
402 // Keep merging while any pass still makes progress. Using "did this pass
403 // merge anything?" as the loop guard (instead of re-testing every node)
404 // also avoids spinning forever on a node that is too small/thin but has no
405 // valid neighbour to merge into.
406 bool merged_any = true;
407 while (merged_any) {
408 merged_any = false;
409
410 for (const Node_ptr& n : get_nodes()) {
411 if (n->area() == 0)
412 continue;
413
414 bool needs_merge = n->area() < static_cast<size_t>(min_area);
415 if (!needs_merge && min_thickness > 0) {
416 // too thin == no inscribed disk of radius min_thickness/2 fits.
417 needs_merge = 2.0f * max_inscribed_radius(n) < static_cast<float>(min_thickness);
418 }
419 if (!needs_merge)
420 continue;
421
422 ImageLib::RGBPixel<uint8_t> col = n->color();
423
424 Node_ptr best_neighbor = nullptr;
425 float best_score = std::numeric_limits<float>::max();
426 for (const Node_ptr& ne : n->edges()) {
427 if (ne->area() > 0) {
428 float cdist = ImageLib::RGBPixel<uint8_t>::colorDistance(ne->color(), col);
429 float score = static_cast<float>(ne->area()) + 10.f * cdist;
430 if (score < best_score) {
431 best_score = score;
432 best_neighbor = ne;
433 }
434 }
435 }
436
437 // no valid neighbor found, skip this node
438 if (!best_neighbor) {
439 continue;
440 }
441
442 if (best_neighbor->area() >= n->area()) {
443 merge_nodes(best_neighbor, n);
444 } else {
445 merge_nodes(n, best_neighbor);
446 }
447 merged_any = true;
448 }
449
450 clear_unconnected_nodes();
451 }
452}
uint8_t getPixel(const std::vector< uint8_t > &img, int w, int h, int x, int y)
Definition graph.h:52
std::vector< uint8_t > analyzeJunctions(const std::vector< uint8_t > &skel, int w, int h)
Definition graph.cpp:223
Definition node.h:38