VMTK
Loading...
Searching...
No Matches
vtkvmtkPolyDataBoundaryLabeler.cxx
Go to the documentation of this file.
1/*=========================================================================
2
3Program: VMTK
4
5 Copyright (c) Luca Antiga, David Steinman. All rights reserved.
6 See LICENSE file for details.
7
8 Portions of this code are covered under the VTK copyright.
9 See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm
10 for details.
11
12 This software is distributed WITHOUT ANY WARRANTY; without even
13 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 PURPOSE. See the above copyright notices for more information.
15
16=========================================================================*/
17
19
20#include "vtkCellData.h"
21#include "vtkDataArray.h"
22#include "vtkDoubleArray.h"
23#include "vtkIdList.h"
24#include "vtkIdTypeArray.h"
25#include "vtkIntArray.h"
26#include "vtkInformation.h"
27#include "vtkInformationVector.h"
28#include "vtkMath.h"
29#include "vtkNew.h"
30#include "vtkObjectFactory.h"
31#include "vtkPointData.h"
32#include "vtkPoints.h"
33#include "vtkPolyData.h"
34#include "vtkPolyLine.h"
35
39
40#include <algorithm>
41#include <map>
42#include <vector>
43
44namespace
45{
46
47// How far the point of the ring nearest to, and furthest from, origin actually is. The furthest
48// is what says whether the boundary lies entirely within a distance of the origin; the nearest is
49// what ranks one boundary against another.
50void DistancesFromPoint(vtkPolyData* surface, const std::vector<vtkIdType>& ring, const double origin[3], double& nearestDistance, double& furthestDistance)
51{
52 double nearestDistance2 = 0.0;
53 double furthestDistance2 = 0.0;
54 for (size_t j=0; j<ring.size(); j++)
55 {
56 double point[3];
57 surface->GetPoint(ring[j],point);
58 double distance2 = vtkMath::Distance2BetweenPoints(origin,point);
59 if (j == 0 || distance2 < nearestDistance2)
60 {
61 nearestDistance2 = distance2;
62 }
63 if (distance2 > furthestDistance2)
64 {
65 furthestDistance2 = distance2;
66 }
67 }
68 nearestDistance = sqrt(nearestDistance2);
69 furthestDistance = sqrt(furthestDistance2);
70}
71
72}
73
75
98
100{
101 this->SetBoundaryLabelsArrayName(nullptr);
102 this->SetBoundaryPointOrderArrayName(nullptr);
103
104 this->SetPlaneOrigins(nullptr);
105 this->SetPlaneNormals(nullptr);
106 this->SetPlaneLabels(nullptr);
107
108 this->BoundaryLabels->Delete();
109 this->BoundaryLabels = nullptr;
110 this->UnmatchedPlaneLabels->Delete();
111 this->UnmatchedPlaneLabels = nullptr;
112}
113
115 vtkInformation *vtkNotUsed(request),
116 vtkInformationVector **inputVector,
117 vtkInformationVector *outputVector)
118{
119 vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
120 vtkInformation *outInfo = outputVector->GetInformationObject(0);
121
122 vtkPolyData *input = vtkPolyData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT()));
123 vtkPolyData *output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));
124
125 // The mesh is untouched; only the two arrays are new, so pass everything through and add them
126 // to the output's own point data rather than to the input's.
127 output->CopyStructure(input);
128 output->GetPointData()->PassData(input->GetPointData());
129 output->GetCellData()->PassData(input->GetCellData());
130
131 this->NumberOfBoundaries = 0;
132 this->BoundaryLabels->Initialize();
133 this->UnmatchedPlaneLabels->Initialize();
134
137 {
138 vtkErrorMacro(<<"Both BoundaryLabelsArrayName and BoundaryPointOrderArrayName have to be set.");
139 return 1;
140 }
141
142 const vtkIdType invalidLabel = vtkvmtkBoundaryLabels::GetInvalidBoundaryLabel();
143 vtkIdType numberOfPoints = input->GetNumberOfPoints();
144
145 vtkNew<vtkIntArray> labelsArray;
146 labelsArray->SetName(this->BoundaryLabelsArrayName);
147 labelsArray->SetNumberOfTuples(numberOfPoints);
148 labelsArray->FillComponent(0,static_cast<double>(invalidLabel));
149
150 vtkNew<vtkIntArray> orderArray;
151 orderArray->SetName(this->BoundaryPointOrderArrayName);
152 orderArray->SetNumberOfTuples(numberOfPoints);
153 orderArray->FillComponent(0,static_cast<double>(invalidLabel));
154
155 vtkNew<vtkvmtkPolyDataBoundaryExtractor> boundaryExtractor;
156 boundaryExtractor->SetInputData(input);
157 boundaryExtractor->Update();
158 vtkPolyData* boundaries = boundaryExtractor->GetOutput();
159 vtkDataArray* boundaryPointIds = boundaries->GetPointData()->GetScalars();
160
161 // The points of each boundary, as ids into the input, in the order the extractor walked them.
162 std::vector<std::vector<vtkIdType> > rings;
163 for (vtkIdType boundaryIndex=0; boundaryIndex<boundaries->GetNumberOfCells(); boundaryIndex++)
164 {
165 vtkPolyLine* boundary = vtkPolyLine::SafeDownCast(boundaries->GetCell(boundaryIndex));
166 if (!boundary || !boundaryPointIds)
167 {
168 continue;
169 }
170 vtkIdType numberOfBoundaryPoints = boundary->GetNumberOfPoints();
171 std::vector<vtkIdType> ring;
172 ring.reserve(numberOfBoundaryPoints);
173 for (vtkIdType j=0; j<numberOfBoundaryPoints; j++)
174 {
175 ring.push_back(static_cast<vtkIdType>(vtkMath::Round(
176 boundaryPointIds->GetComponent(boundary->GetPointId(j),0))));
177 }
178 rings.push_back(ring);
179 }
180
181 vtkIdType numberOfBoundaries = static_cast<vtkIdType>(rings.size());
182 std::vector<vtkIdType> labels(rings.size(),invalidLabel);
183
184 // Labels already in use, so that a boundary given a fresh one never collides with a label a
185 // end point asked for, or with one that is on the surface already but on no boundary any more.
186 // It starts at the wall rather than at invalidLabel because a label is a cap's cell entity id,
187 // and the first id a cap may take is the one above the wall (see CellEntityIdOffset).
188 vtkIdType highestLabelInUse = this->CellEntityIdOffset;
189
190 vtkIdType numberOfPlanes = 0;
192 && this->PlaneOrigins)
193 {
194 numberOfPlanes = this->PlaneOrigins->GetNumberOfPoints();
195 if (this->LabelingMode == ON_PLANE
196 && this->PlaneNormals && this->PlaneNormals->GetNumberOfTuples() < numberOfPlanes)
197 {
198 numberOfPlanes = this->PlaneNormals->GetNumberOfTuples();
199 }
200 }
201 std::vector<vtkIdType> planeLabels(numberOfPlanes,invalidLabel);
202 std::vector<bool> planeMatched(numberOfPlanes,false);
203 for (vtkIdType planeIndex=0; planeIndex<numberOfPlanes; planeIndex++)
204 {
205 planeLabels[planeIndex] = this->PlaneLabels && planeIndex < this->PlaneLabels->GetNumberOfIds()
206 ? this->PlaneLabels->GetId(planeIndex) : planeIndex+1+this->CellEntityIdOffset;
207 if (planeLabels[planeIndex] > highestLabelInUse)
208 {
209 highestLabelInUse = planeLabels[planeIndex];
210 }
211 }
212
213 switch (this->LabelingMode)
214 {
216 {
217 for (vtkIdType planeIndex=0; planeIndex<numberOfPlanes; planeIndex++)
218 {
219 double origin[3];
220 this->PlaneOrigins->GetPoint(planeIndex,origin);
221 vtkIdType nearestBoundary = -1;
222 double nearestDistance = 0.0;
223 for (vtkIdType boundaryIndex=0; boundaryIndex<numberOfBoundaries; boundaryIndex++)
224 {
225 double boundaryNearestDistance, boundaryFurthestDistance;
226 DistancesFromPoint(input,rings[boundaryIndex],origin,boundaryNearestDistance,boundaryFurthestDistance);
227 // Entirely within, or not a candidate at all: one point of the boundary out beyond the
228 // limit and it is passed over, however near the rest of it comes.
229 if (this->MaximumDistanceFromPlaneOrigin > 0.0
230 && boundaryFurthestDistance > this->MaximumDistanceFromPlaneOrigin)
231 {
232 continue;
233 }
234 if (nearestBoundary == -1 || boundaryNearestDistance < nearestDistance)
235 {
236 nearestBoundary = boundaryIndex;
237 nearestDistance = boundaryNearestDistance;
238 }
239 }
240 if (nearestBoundary == -1)
241 {
242 continue;
243 }
244 // A boundary an earlier plane already took is not handed over: the second plane is
245 // reported unmatched instead, rather than silently moved to a boundary it did not choose.
246 if (labels[nearestBoundary] != invalidLabel)
247 {
248 continue;
249 }
250 labels[nearestBoundary] = planeLabels[planeIndex];
251 planeMatched[planeIndex] = true;
252 }
253 break;
254 }
255 case ON_PLANE:
256 {
257 if (this->MaximumDistanceFromPlane <= 0.0)
258 {
259 vtkErrorMacro(<<"MaximumDistanceFromPlane has to be positive in the OnPlane mode; no boundary was matched to a plane.");
260 break;
261 }
262 if (!this->PlaneNormals)
263 {
264 vtkErrorMacro(<<"PlaneNormals has to be set in the OnPlane mode; no boundary was matched to a plane.");
265 break;
266 }
267 // A plane at a time, taking the nearest of the boundaries that qualify for it. Doing it
268 // the other way round - a boundary at a time, first plane that fits - would let two
269 // boundaries lying in the same plane be told apart by nothing but which of them the
270 // extractor happened to reach first, which is the dependence on mesh numbering this whole
271 // arrangement exists to be rid of.
272 for (vtkIdType planeIndex=0; planeIndex<numberOfPlanes; planeIndex++)
273 {
274 double origin[3], normal[3];
275 this->PlaneOrigins->GetPoint(planeIndex,origin);
276 this->PlaneNormals->GetTuple(planeIndex,normal);
277 if (vtkMath::Normalize(normal) == 0.0)
278 {
279 continue;
280 }
281
282 vtkIdType nearestBoundary = -1;
283 double nearestDistance = 0.0;
284 vtkIdType numberOfQualifyingBoundaries = 0;
285 for (vtkIdType boundaryIndex=0; boundaryIndex<numberOfBoundaries; boundaryIndex++)
286 {
287 // A boundary an earlier plane already took carries that plane's label and is not on
288 // offer to this one.
289 if (labels[boundaryIndex] != invalidLabel)
290 {
291 continue;
292 }
293 // A plane is infinite and a surface is not, so lying in the plane is not on its own
294 // enough: the boundary has to be near this origin too, or a boundary on another branch
295 // that happens to be coplanar with this cut would be claimed by it.
296 double boundaryNearestDistance, boundaryFurthestDistance;
297 DistancesFromPoint(input,rings[boundaryIndex],origin,boundaryNearestDistance,boundaryFurthestDistance);
298 if (this->MaximumDistanceFromPlaneOrigin > 0.0
299 && boundaryFurthestDistance > this->MaximumDistanceFromPlaneOrigin)
300 {
301 continue;
302 }
303 // Every point of the boundary has to be in the plane, so that a boundary lying only
304 // partly in it - a hole the surface already had, or another cut's - is left alone
305 // rather than claimed by the wrong plane.
306 bool inPlane = true;
307 for (size_t j=0; j<rings[boundaryIndex].size(); j++)
308 {
309 double boundaryPoint[3];
310 input->GetPoint(rings[boundaryIndex][j],boundaryPoint);
311 double offset[3];
312 for (int k=0; k<3; k++)
313 {
314 offset[k] = boundaryPoint[k] - origin[k];
315 }
316 if (fabs(vtkMath::Dot(offset,normal)) >= this->MaximumDistanceFromPlane)
317 {
318 inPlane = false;
319 break;
320 }
321 }
322 if (!inPlane)
323 {
324 continue;
325 }
326 numberOfQualifyingBoundaries++;
327 if (nearestBoundary == -1 || boundaryNearestDistance < nearestDistance)
328 {
329 nearestBoundary = boundaryIndex;
330 nearestDistance = boundaryNearestDistance;
331 }
332 }
333
334 if (nearestBoundary == -1)
335 {
336 continue;
337 }
338 if (numberOfQualifyingBoundaries > 1)
339 {
340 // Answerable by geometry, but only just: say so, because it usually means
341 // MaximumDistanceFromPlaneOrigin is looser than the surface warrants.
342 vtkWarningMacro(<<numberOfQualifyingBoundaries<<" boundaries lie in the plane of the one labelled "
343 <<planeLabels[planeIndex]<<"; the nearest to its origin was taken.");
344 }
345 labels[nearestBoundary] = planeLabels[planeIndex];
346 planeMatched[planeIndex] = true;
347 }
348 break;
349 }
351 {
352 vtkDataArray* existingLabels = input->GetPointData()->GetArray(this->BoundaryLabelsArrayName);
353 if (existingLabels && existingLabels->GetNumberOfComponents() == 1
354 && existingLabels->GetNumberOfTuples() == numberOfPoints)
355 {
356 for (vtkIdType pointId=0; pointId<numberOfPoints; pointId++)
357 {
358 vtkIdType label = static_cast<vtkIdType>(vtkMath::Round(existingLabels->GetComponent(pointId,0)));
359 if (label > highestLabelInUse)
360 {
361 highestLabelInUse = label;
362 }
363 }
364 // A boundary keeps the label a strict majority of its points agree on. Anything less is
365 // not a boundary that came through a filter intact: a newly cut one is made of new
366 // points, which carry no label of their own or, where a filter interpolated the array
367 // onto them, one that no majority backs.
368 std::map<vtkIdType,std::pair<vtkIdType,vtkIdType> > bestClaimByLabel;
369 std::vector<vtkIdType> claimedLabel(rings.size(),invalidLabel);
370 std::vector<vtkIdType> claimCount(rings.size(),0);
371 for (vtkIdType boundaryIndex=0; boundaryIndex<numberOfBoundaries; boundaryIndex++)
372 {
373 std::map<vtkIdType,vtkIdType> counts;
374 for (size_t j=0; j<rings[boundaryIndex].size(); j++)
375 {
376 vtkIdType label = static_cast<vtkIdType>(vtkMath::Round(
377 existingLabels->GetComponent(rings[boundaryIndex][j],0)));
378 if (label >= 0)
379 {
380 counts[label]++;
381 }
382 }
383 vtkIdType ringSize = static_cast<vtkIdType>(rings[boundaryIndex].size());
384 for (std::map<vtkIdType,vtkIdType>::iterator count=counts.begin(); count!=counts.end(); ++count)
385 {
386 if (count->second * 2 > ringSize)
387 {
388 claimedLabel[boundaryIndex] = count->first;
389 claimCount[boundaryIndex] = count->second;
390 break;
391 }
392 }
393 if (claimedLabel[boundaryIndex] == invalidLabel)
394 {
395 continue;
396 }
397 // A label two boundaries both claim - a cut that split one boundary into two, say -
398 // can only stay with one of them.
399 std::map<vtkIdType,std::pair<vtkIdType,vtkIdType> >::iterator best =
400 bestClaimByLabel.find(claimedLabel[boundaryIndex]);
401 if (best == bestClaimByLabel.end())
402 {
403 bestClaimByLabel[claimedLabel[boundaryIndex]] =
404 std::make_pair(claimCount[boundaryIndex],boundaryIndex);
405 }
406 else
407 {
408 vtkWarningMacro(<<"More than one boundary carries the label "<<claimedLabel[boundaryIndex]
409 <<"; it stays with the one holding it most widely and the others are relabeled.");
410 if (claimCount[boundaryIndex] > best->second.first)
411 {
412 best->second = std::make_pair(claimCount[boundaryIndex],boundaryIndex);
413 }
414 }
415 }
416 for (std::map<vtkIdType,std::pair<vtkIdType,vtkIdType> >::iterator best=bestClaimByLabel.begin();
417 best!=bestClaimByLabel.end(); ++best)
418 {
419 labels[best->second.second] = best->first;
420 }
421 }
422 break;
423 }
425 default:
426 {
427 for (vtkIdType boundaryIndex=0; boundaryIndex<numberOfBoundaries; boundaryIndex++)
428 {
429 // The id vtkvmtkCapPolyData gives the cap of the boundary in this position when it is
430 // left to number the caps itself, so that labeling a surface this way and not labeling
431 // it at all come to the same thing.
432 labels[boundaryIndex] = boundaryIndex+1+this->CellEntityIdOffset;
433 if (labels[boundaryIndex] > highestLabelInUse)
434 {
435 highestLabelInUse = labels[boundaryIndex];
436 }
437 }
438 break;
439 }
440 }
441
442 for (vtkIdType boundaryIndex=0; boundaryIndex<numberOfBoundaries; boundaryIndex++)
443 {
444 if (labels[boundaryIndex] > highestLabelInUse)
445 {
446 highestLabelInUse = labels[boundaryIndex];
447 }
448 }
449 for (vtkIdType boundaryIndex=0; boundaryIndex<numberOfBoundaries; boundaryIndex++)
450 {
451 if (labels[boundaryIndex] == invalidLabel)
452 {
453 labels[boundaryIndex] = ++highestLabelInUse;
454 }
455 }
456
457 if (this->Annular)
458 {
459 this->LabelAnnularPairs(boundaries,labels);
460 }
461
462 for (vtkIdType boundaryIndex=0; boundaryIndex<numberOfBoundaries; boundaryIndex++)
463 {
464 for (size_t j=0; j<rings[boundaryIndex].size(); j++)
465 {
466 labelsArray->SetValue(rings[boundaryIndex][j],static_cast<int>(labels[boundaryIndex]));
467 orderArray->SetValue(rings[boundaryIndex][j],static_cast<int>(j));
468 }
469 this->BoundaryLabels->InsertNextId(labels[boundaryIndex]);
470 }
471
472 for (vtkIdType planeIndex=0; planeIndex<numberOfPlanes; planeIndex++)
473 {
474 if (!planeMatched[planeIndex])
475 {
476 this->UnmatchedPlaneLabels->InsertNextId(planeLabels[planeIndex]);
477 }
478 }
479
480 this->NumberOfBoundaries = numberOfBoundaries;
481
482 output->GetPointData()->AddArray(labelsArray);
483 output->GetPointData()->AddArray(orderArray);
484
485 return 1;
486}
487
488void vtkvmtkPolyDataBoundaryLabeler::LabelAnnularPairs(vtkPolyData* boundaries, std::vector<vtkIdType>& labels)
489{
490 vtkIdType numberOfBoundaries = boundaries->GetNumberOfCells();
491 if (numberOfBoundaries < 2)
492 {
493 return;
494 }
495
496 // Barycenter and mean radius of each boundary: the first pairs them, the second says which of
497 // a pair is the inner one.
498 std::vector<std::vector<double> > barycenters(numberOfBoundaries,std::vector<double>(3,0.0));
499 std::vector<double> meanRadii(numberOfBoundaries,0.0);
500 for (vtkIdType boundaryIndex=0; boundaryIndex<numberOfBoundaries; boundaryIndex++)
501 {
502 vtkPolyLine* boundary = vtkPolyLine::SafeDownCast(boundaries->GetCell(boundaryIndex));
503 if (!boundary)
504 {
505 continue;
506 }
507 double barycenter[3];
508 vtkvmtkBoundaryReferenceSystems::ComputeBoundaryBarycenter(boundary->GetPoints(),barycenter);
509 for (int j=0; j<3; j++)
510 {
511 barycenters[boundaryIndex][j] = barycenter[j];
512 }
513 meanRadii[boundaryIndex] = vtkvmtkBoundaryReferenceSystems::ComputeBoundaryMeanRadius(boundary->GetPoints(),barycenter);
514 }
515
516 // Each boundary still unpaired takes the closest boundary still unpaired, which is how the
517 // annular cappers pair them too.
518 std::vector<bool> paired(numberOfBoundaries,false);
519 for (vtkIdType boundaryIndex=0; boundaryIndex<numberOfBoundaries; boundaryIndex++)
520 {
521 if (paired[boundaryIndex])
522 {
523 continue;
524 }
525 vtkIdType closestIndex = -1;
526 double closestDistance2 = 0.0;
527 for (vtkIdType candidateIndex=boundaryIndex+1; candidateIndex<numberOfBoundaries; candidateIndex++)
528 {
529 if (paired[candidateIndex])
530 {
531 continue;
532 }
533 double distance2 = vtkMath::Distance2BetweenPoints(&barycenters[boundaryIndex][0],&barycenters[candidateIndex][0]);
534 if (closestIndex == -1 || distance2 < closestDistance2)
535 {
536 closestIndex = candidateIndex;
537 closestDistance2 = distance2;
538 }
539 }
540 if (closestIndex == -1)
541 {
542 // An odd boundary with nothing left to pair with keeps the label it was given.
543 vtkWarningMacro(<<"Annular labeling: the boundary labelled "<<labels[boundaryIndex]
544 <<" has no partner, so it keeps its label and no outer label is derived from it.");
545 break;
546 }
547
548 paired[boundaryIndex] = true;
549 paired[closestIndex] = true;
550
551 vtkIdType innerIndex = boundaryIndex;
552 vtkIdType outerIndex = closestIndex;
553 if (meanRadii[outerIndex] < meanRadii[innerIndex])
554 {
555 std::swap(innerIndex,outerIndex);
556 }
557
558 // The inner boundary keeps the label it was given; the outer one is named after it, so the
559 // pair reads as one vessel end and the inner label is the lower of the two.
560 labels[outerIndex] = labels[innerIndex] + this->AnnularOuterBoundaryOffset;
561 }
562}
563
564void vtkvmtkPolyDataBoundaryLabeler::PrintSelf(std::ostream& os, vtkIndent indent)
565{
566 this->Superclass::PrintSelf(os,indent);
567}
static const char * GetDefaultBoundaryLabelsArrayName()
static const char * GetDefaultBoundaryPointOrderArrayName()
static vtkIdType GetInvalidBoundaryLabel()
static void ComputeBoundaryBarycenter(vtkPoints *points, double barycenter[3])
static double ComputeBoundaryMeanRadius(vtkPoints *points, double barycenter[3])
Give each open boundary of a surface a label that stays with it.
virtual void SetPlaneNormals(vtkDoubleArray *)
void PrintSelf(std::ostream &os, vtkIndent indent) override
void LabelAnnularPairs(vtkPolyData *boundaries, std::vector< vtkIdType > &labels)
virtual void SetBoundaryLabelsArrayName(const char *)
virtual void SetBoundaryPointOrderArrayName(const char *)
virtual void SetPlaneLabels(vtkIdList *)
virtual void SetPlaneOrigins(vtkPoints *)
int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *) override
vtkStandardNewMacro(vtkvmtkPolyDataBoundaryLabeler)