Blame view

include/grmGraphOperations.txx 13.1 KB
84788f22   Pierre Lassalle   Add the GRM Remot...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*=========================================================================

  Program: Generic Region Merging Library
  Language: C++
  author: Lassalle Pierre
  contact: lassallepierre34@gmail.com



  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved


     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
b825dc37   Pierre Lassalle   Header fixes.
18
19
#ifndef GRM_GRAPH_OPERATIONS_TXX
#define GRM_GRAPH_OPERATIONS_TXX
84788f22   Pierre Lassalle   Add the GRM Remot...
20
#include <otbImageFileReader.h>
5367de74   Rémi Cresson (IRSTEA)   FIX: add raffaele...
21
#include "grmGraphOperations.h"
d5966982   Pierre Lassalle   Header fixes.
22

84788f22   Pierre Lassalle   Add the GRM Remot...
23
24
25
26
27
28
29
30
namespace grm
{	
	template<class TSegmenter>
	void GraphOperations<TSegmenter>::InitNodes(ImageType * inputImg,
												SegmenterType& seg,
												CONNECTIVITY mask)
	{
		unsigned int width, height;
5367de74   Rémi Cresson (IRSTEA)   FIX: add raffaele...
31
		
4f606e07   Rémi Cresson (IRSTEA)   ENH: implement Ra...
32
33
34
35
36
37
38
39
40
41
		{
			width = inputImg->GetLargestPossibleRegion().GetSize()[0];
			height = inputImg->GetLargestPossibleRegion().GetSize()[1];
		}
		
		const long unsigned int num_nodes = width * height;

		seg.m_Graph.m_Nodes.reserve(num_nodes);

		for(long unsigned int i = 0;
a57529d7   raffaele.gaetano   FIX: platform che...
42
			i < num_nodes;
4f606e07   Rémi Cresson (IRSTEA)   ENH: implement Ra...
43
44
45
46
47
48
49
50
51
52
53
54
55
			++i)
		{
			NodePointerType n(new NodeType);
			n->m_Id = i;
			n->m_Valid = true;
			n->m_Expired = false;
			n->m_IsMerged = true; // force to compute costs for the first iteration
			n->m_Perimeter = 4;
			n->m_Area = 1;
			n->m_Bbox.m_UX = i % width;
			n->m_Bbox.m_UY = i / width;
			n->m_Bbox.m_W = 1;
			n->m_Bbox.m_H = 1;
a57529d7   raffaele.gaetano   FIX: platform che...
56

4f606e07   Rémi Cresson (IRSTEA)   ENH: implement Ra...
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
			// An initial contour is the one aroun a pixel
			ContourOperator::Push1(n->m_Contour);
			ContourOperator::Push2(n->m_Contour);
			ContourOperator::Push3(n->m_Contour);
			ContourOperator::Push0(n->m_Contour);
			
			seg.m_Graph.m_Nodes.push_back(n);
		}

		if(mask == FOUR)
		{
			for(auto& r : seg.m_Graph.m_Nodes)
			{
				long int neighborhood[4];
				FOURNeighborhood(neighborhood, r->m_Id, width, height);
				for(short j = 0; j < 4; ++j)
				{
					if(neighborhood[j] > -1)
84788f22   Pierre Lassalle   Add the GRM Remot...
75
						r->m_Edges.push_back(EdgeType( seg.m_Graph.m_Nodes[neighborhood[j]], 0, 1));
84788f22   Pierre Lassalle   Add the GRM Remot...
76
77
78
79
80
81
				}
			}
		}
		else
		{
			for(auto& r : seg.m_Graph.m_Nodes)
ea78cfb9   raffaele.gaetano   FIX: Changed long...
82
			{
84788f22   Pierre Lassalle   Add the GRM Remot...
83
84
85
86
87
88
89
90
91
92
				long int neighborhood[8];
				EIGHTNeighborhood(neighborhood, r->m_Id, width, height);
				for(short j = 0; j < 8; ++j)
				{
					if(neighborhood[j] > -1)
					{
						if(j % 2 > 0)
							r->m_Edges.push_back(EdgeType( seg.m_Graph.m_Nodes[neighborhood[j]], 0, 0));
						else
							r->m_Edges.push_back(EdgeType( seg.m_Graph.m_Nodes[neighborhood[j]], 0, 1));
5367de74   Rémi Cresson (IRSTEA)   FIX: add raffaele...
93
94
					}
				}
84788f22   Pierre Lassalle   Add the GRM Remot...
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
			}
		}
		seg.InitFromImage();
	}

	template<class TSegmenter>
	void GraphOperations<TSegmenter>::UpdateMergingCosts(SegmenterType& seg)
	{		
		float min_cost;
		long unsigned int min_id  = 0;
		std::size_t idx, min_idx;

		for(auto& r : seg.m_Graph.m_Nodes)
		{
			for(auto& edge : r->m_Edges)
				edge.m_CostUpdated = false;
		}

		for(auto& r : seg.m_Graph.m_Nodes)
		{
			min_cost = std::numeric_limits<float>::max();
			idx = 0;
			min_idx = 0;

			r->m_Expired = false;
			r->m_Valid = true;

			for(auto& edge : r->m_Edges)
			{
				auto neighborR = edge.GetRegion();

				// Compute the cost if necessary
				if(!edge.m_CostUpdated && (neighborR->m_IsMerged || r->m_IsMerged))
				{
					auto edgeFromNeighborToR = FindEdge(neighborR, r);
					edge.m_Cost = seg.ComputeMergingCost(r, neighborR);
					edgeFromNeighborToR->m_Cost = edge.m_Cost;
					edge.m_CostUpdated = true;
					edgeFromNeighborToR->m_CostUpdated = true;
				}

				// Check if the cost of the edge is the minimum
				if(min_cost > edge.m_Cost)
				{
					min_cost = edge.m_Cost;
					min_id = neighborR->m_Id;
					min_idx = idx;
				}
				else if(min_cost == edge.m_Cost)
				{
					if(min_id > neighborR->m_Id)
					{
						min_id = neighborR->m_Id;
ea78cfb9   raffaele.gaetano   FIX: Changed long...
148
149
150
151
						min_idx = idx;
					}
				}
				++idx;	
84788f22   Pierre Lassalle   Add the GRM Remot...
152
153
154
155
156
157
			}

			assert(min_idx < r->m_Edges.size());
			std::swap(r->m_Edges[0], r->m_Edges[min_idx]);
				
		}
ea78cfb9   raffaele.gaetano   FIX: Changed long...
158

84788f22   Pierre Lassalle   Add the GRM Remot...
159
160
161
		// Reset the merge flag for all the regions.
		for(auto& r : seg.m_Graph.m_Nodes)
			r->m_IsMerged = false;
ea78cfb9   raffaele.gaetano   FIX: Changed long...
162
	}
84788f22   Pierre Lassalle   Add the GRM Remot...
163
164
165
166
167
168
169

	template<class TSegmenter>
	typename GraphOperations<TSegmenter>::NodePointerType
	GraphOperations<TSegmenter>::CheckLMBF(NodePointerType a, float t)
	{
		if(a->m_Valid)
		{
84788f22   Pierre Lassalle   Add the GRM Remot...
170
			float cost = a->m_Edges.front().m_Cost;
84788f22   Pierre Lassalle   Add the GRM Remot...
171
			
84788f22   Pierre Lassalle   Add the GRM Remot...
172
			if(cost < t)
c4115e48   Rémi Cresson (IRSTEA)   REFAC: some refac
173
			{
84788f22   Pierre Lassalle   Add the GRM Remot...
174
175
176
177
178
179
				NodePointerType b = a->m_Edges.front().GetRegion();

				if( b->m_Valid)
				{
					NodePointerType best_b = b->m_Edges.front().GetRegion();

ea78cfb9   raffaele.gaetano   FIX: Changed long...
180
181
182
183
					if(a == best_b)
					{
						if(a->m_Id < b->m_Id)
							return a;
84788f22   Pierre Lassalle   Add the GRM Remot...
184
185
186
187
188
189
190
191
192
193
194
195
196
197
						else
							return b;
					}
					else
						return NodePointerType();
				}
				else
					return NodePointerType();
			}
			else
				return NodePointerType();
		}
		else
			return NodePointerType();
84788f22   Pierre Lassalle   Add the GRM Remot...
198
	}
84788f22   Pierre Lassalle   Add the GRM Remot...
199

c4115e48   Rémi Cresson (IRSTEA)   REFAC: some refac
200
201
	template<class TSegmenter>
	typename GraphOperations<TSegmenter>::NodePointerType
84788f22   Pierre Lassalle   Add the GRM Remot...
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
	GraphOperations<TSegmenter>::CheckBF(NodePointerType a, float t)
	{
		if(a->m_Valid)
		{
			float cost = a->m_Edges.front().m_Cost;

			if( cost < t )
			{
				NodePointerType b = a->m_Edges.front().GetRegion();

				if(b->m_Valid)
				{
					if( a->m_Id < b->m_Id )
						return a;
					else
						return b;
				}
				else
					return NodePointerType();
			}
			else
				return NodePointerType();
		}
		else
			return NodePointerType();
	}

	template<class TSegmenter>
	typename GraphOperations<TSegmenter>::EdgeIterator
	GraphOperations<TSegmenter>::FindEdge(NodePointerType n, NodePointerType target)
	{
		return std::find_if(n->m_Edges.begin(), n->m_Edges.end(),[&](EdgeType& e)->bool{
				return e.GetRegion() == target;
			});
	}

	template<class TSegmenter>
	void
	GraphOperations<TSegmenter>::UpdateNeighbors(NodePointerType a, NodePointerType b)
	{
		unsigned int boundary;

		/* Explore the neighbors of b */
		for (auto& edge : b->m_Edges)
		{
			// Retrieve the edge targeting node b.
			auto neigh_b = edge.GetRegion();
			auto toB = FindEdge(neigh_b, b);

			/* If the edge tageting to node b is the first then
			   the corresponding node is not valid anymore. */
			if(toB == neigh_b->m_Edges.begin())
				neigh_b->m_Valid = false;

			/* Keep in memory the boundary between node b
			   and node neigh_b */
			boundary = edge.m_Boundary;

			/*
			  We can remove safely the edge from node neigh_b
			  targeting to node b
			*/
			neigh_b->m_Edges.erase(toB);

			if(neigh_b != a)
			{
				/* Retrieve the edge targeting to node a. */
				auto toA = FindEdge(neigh_b, a);

				if( toA == neigh_b->m_Edges.end() )
				{
					/* No edge exists between node a and node neigh_b. */

					/* Add an edge from node neigh_b targeting node a. */
					neigh_b->m_Edges.push_back(EdgeType(a, 0, boundary));

					/* Add an edge from node a targeting node neigh_b. */
					a->m_Edges.push_back(EdgeType(neigh_b, 0, boundary));
				}
				else
				{
					/* An edge exists between node a and node neigh_b. */

					/* Increment the boundary of the edge from node neigh_b
					   targeting to node a. */
					toA->m_Boundary += boundary;

					/* Increment the boundary of the edge from node a
					   targeting to node neigh_b. */
					auto toNeighB = FindEdge(a, neigh_b);
					toNeighB->m_Boundary += boundary;
				}
			}
			
		}
		
	}

	template<class TSegmenter>
	void
	GraphOperations<TSegmenter>::UpdateInternalAttributes(NodePointerType a,
														  NodePointerType b,
														  const unsigned int width)
	{

		lp::BoundingBox mergedBBox;
		lp::Contour mergedContour;		
		ContourOperator::MergeContour(mergedContour, mergedBBox, a->m_Contour,
									  b->m_Contour, a->m_Bbox, b->m_Bbox,
									  a->m_Id, b->m_Id, width);
		
		/* Step 1: update the bounding box */
		a->m_Bbox = mergedBBox;//MergeBoundingBoxes(a->m_Bbox, b->m_Bbox);

		/* Step 2: update the contour */
		a->m_Contour = mergedContour;

		/* Step 2 : update perimeter and area attributes */
		EdgeIterator toB = FindEdge(a, b);
		a->m_Perimeter += (b->m_Perimeter - 2 * toB->m_Boundary);
		a->m_Area += b->m_Area;
			
		/* Step 2: update the neighborhood */
		UpdateNeighbors(a,b);
		
ea78cfb9   raffaele.gaetano   FIX: Changed long...
327
		/* Step 3: update the node' states */
84788f22   Pierre Lassalle   Add the GRM Remot...
328
329
		a->m_Valid = false;
		b->m_Valid = false;
5367de74   Rémi Cresson (IRSTEA)   FIX: add raffaele...
330
		b->m_Expired = true;
84788f22   Pierre Lassalle   Add the GRM Remot...
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
		a->m_IsMerged = true;
	}

	template<class TSegmenter>
	void
	GraphOperations<TSegmenter>::RemoveExpiredNodes(GraphType& graph)
	{
		NodeIterator nit = std::remove_if(graph.m_Nodes.begin(), graph.m_Nodes.end(), [](NodePointerType r)->bool{
				return r->m_Expired;
			});
		graph.m_Nodes.erase(nit, graph.m_Nodes.end());
	}

	template<class TSegmenter>
	bool
	GraphOperations<TSegmenter>::PerfomOneIterationWithLMBF(SegmenterType& seg)
	{
		bool merged = false;

		/* Update the costs of merging between adjacent nodes */
		UpdateMergingCosts(seg);

		for(auto& region : seg.m_Graph.m_Nodes)
		{
			
			auto res_node = CheckLMBF(region, seg.GetThreshold());

			if(res_node)
				{
					seg.UpdateSpecificAttributes(res_node, res_node->m_Edges.front().GetRegion());
					UpdateInternalAttributes(res_node, res_node->m_Edges.front().GetRegion(),
											 seg.GetImageWidth());
					merged = true;
				}
		}

		RemoveExpiredNodes(seg.m_Graph);

		if(seg.m_Graph.m_Nodes.size() < 2)
			return false;

		return merged;
	}

	template<class TSegmenter>
	bool
	GraphOperations<TSegmenter>::PerfomAllIterationsWithLMBFAndConstThreshold(SegmenterType& seg)
	{
		bool merged = true;
		unsigned int maxNumberOfIterations;
		unsigned int iterations = 0;
		unsigned int numberOfIterations = seg.GetNumberOfIterations();

		if(numberOfIterations < 1)
			maxNumberOfIterations = 200;
		else
			maxNumberOfIterations = numberOfIterations;

		while(merged &&
			  iterations < maxNumberOfIterations &&
			  seg.m_Graph.m_Nodes.size() > 1)
		{
			std::cout << "." << std::flush;
			++iterations;

			merged = PerfomOneIterationWithLMBF(seg);
		}
		std::cout << std::endl;
		
		if(seg.m_Graph.m_Nodes.size() < 2)
			return false;

		return merged;
	}

	/* New !!! utilisation of a dither matrix */

	template<class TSegmenter>
	bool
	GraphOperations<TSegmenter>::PerfomAllDitheredIterationsWithBF(SegmenterType& seg)
	{
		bool merged = true;
		unsigned int maxNumberOfIterations;
		unsigned int numberOfIterations = seg.GetNumberOfIterations();
		
		if(numberOfIterations < 1)
			maxNumberOfIterations = 200;
		else
			maxNumberOfIterations = numberOfIterations;

ea78cfb9   raffaele.gaetano   FIX: Changed long...
421
		unsigned int iterations = 0;
84788f22   Pierre Lassalle   Add the GRM Remot...
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479

		while(merged &&
			  iterations < maxNumberOfIterations &&
			  seg.m_Graph.m_Nodes.size() > 1)
		{
			std::cout << "." << std::flush;
			++iterations;

			merged = PerfomOneDitheredIterationWithBF(seg);
		}
		std::cout << std::endl;

		if(seg.m_Graph.m_Nodes.size() < 2)
			return false;

		return merged;
	}

	template<class TSegmenter>
	bool
	GraphOperations<TSegmenter>::PerfomOneDitheredIterationWithBF(SegmenterType& seg)
	{
		bool merged = false;

		std::vector<long unsigned int> randomIndices(seg.m_Graph.m_Nodes.size());
		std::iota(randomIndices.begin(), randomIndices.end(), 0);
		std::shuffle(randomIndices.begin(), randomIndices.end(), std::mt19937{std::random_device{}()});

		for(const auto& i : randomIndices)
		{
			if(seg.m_Graph.m_Nodes[i]->m_Valid == true)
			{
				auto currSeg = seg.m_Graph.m_Nodes[i];
			
				// This segment is marked as used.
				currSeg->m_Valid = false;

				// Compute cost with all its neighbors
				ComputeMergingCostsUsingDither(currSeg, seg);

				// Get the most similar segment
				auto bestSeg = currSeg->m_Edges.front().GetRegion();

				if(currSeg->m_Edges.front().m_Cost < seg.GetThreshold() && !bestSeg->m_Expired)
				{
					merged = true;
				
					if(currSeg->m_Id < bestSeg->m_Id)
					{
						seg.UpdateSpecificAttributes(currSeg, bestSeg);
						UpdateInternalAttributes(currSeg, bestSeg, seg.GetImageWidth());

						for(auto& edge : currSeg->m_Edges)
						{
							edge.m_CostUpdated = false;
							auto toNeigh = FindEdge(edge.GetRegion(), currSeg);
							toNeigh->m_CostUpdated = false;
						}
5367de74   Rémi Cresson (IRSTEA)   FIX: add raffaele...
480
					}
84788f22   Pierre Lassalle   Add the GRM Remot...
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
					else
					{
						seg.UpdateSpecificAttributes(bestSeg, currSeg);
						UpdateInternalAttributes(bestSeg, currSeg, seg.GetImageWidth());

						for(auto& edge : bestSeg->m_Edges)
						{
							edge.m_CostUpdated = false;
							auto toNeigh = FindEdge(edge.GetRegion(), bestSeg);
							toNeigh->m_CostUpdated = false;
						}
					}
				}
			}
		}

		RemoveExpiredNodes(seg.m_Graph);

		// Mark all the segments to be valid

		if(seg.m_Graph.m_Nodes.size() < 2)
			return false;

		for(auto& r : seg.m_Graph.m_Nodes)
			r->m_Valid = true;

		return merged;
	}

	template<class TSegmenter>
	void GraphOperations<TSegmenter>::ComputeMergingCostsUsingDither(NodePointerType r, SegmenterType& seg)
	{

		float min_cost = std::numeric_limits<float>::max();
		std::size_t idx = 0, min_idx = 0;


		for(auto& edge : r->m_Edges)
		{
5367de74   Rémi Cresson (IRSTEA)   FIX: add raffaele...
520
			// Compute the cost if the neighbor is not expired and the cost has to be updated
84788f22   Pierre Lassalle   Add the GRM Remot...
521
522
			if(!edge.GetRegion()->m_Expired)
			{
5367de74   Rémi Cresson (IRSTEA)   FIX: add raffaele...
523
				auto neighborR = edge.GetRegion();
84788f22   Pierre Lassalle   Add the GRM Remot...
524
525
526

				// Compute the cost if necessary
				if(!edge.m_CostUpdated)
4f606e07   Rémi Cresson (IRSTEA)   ENH: implement Ra...
527
				{