File: BinaryImageToMeshFilter.h

package info (click to toggle)
ants 2.1.0-5
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 10,656 kB
  • sloc: cpp: 84,137; sh: 11,419; perl: 694; xml: 115; makefile: 74; python: 48
file content (520 lines) | stat: -rw-r--r-- 16,592 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
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
327
328
329
330
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
421
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
480
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
520
/********************************************************************************
 * Create a VTK mesh from the white matter image
 *******************************************************************************/
#ifndef __BinaryImageToMeshFilter_h_
#define __BinaryImageToMeshFilter_h_
#include <vtkSmartPointer.h>

#include "itkImage.h"
#include "itkResampleImageFilter.h"
#include "itkWindowedSincInterpolateImageFunction.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
#include "itkAntiAliasBinaryImageFilter.h"
#include "itkUnaryFunctorImageFilter.h"
// #include "itkBinaryWellComposed3DImageFilter.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkCommand.h"

#include <vtkCellArray.h>
#include <vtkPolyData.h>
#include <vtkTriangleFilter.h>
#include <vtkImageMarchingCubes.h>
#include <vtkImageImport.h>
#include <itkVTKImageExport.h>
#include <vtkDecimatePro.h>
#include <vtkPolyDataConnectivityFilter.h>
#include <vtkStripper.h>
#include <vtkCleanPolyData.h>
#include <vtkSmoothPolyDataFilter.h>
#include <vtkImageData.h>

#include <iostream>

using namespace std;

template <class TImage>
void ConnectITKToVTK(itk::VTKImageExport<TImage> *fltExport, vtkImageImport *fltImport)
{
  fltImport->SetUpdateInformationCallback( fltExport->GetUpdateInformationCallback() );
  fltImport->SetPipelineModifiedCallback( fltExport->GetPipelineModifiedCallback() );
  fltImport->SetWholeExtentCallback( fltExport->GetWholeExtentCallback() );
  fltImport->SetSpacingCallback( fltExport->GetSpacingCallback() );
  fltImport->SetOriginCallback( fltExport->GetOriginCallback() );
  fltImport->SetScalarTypeCallback( fltExport->GetScalarTypeCallback() );
  fltImport->SetNumberOfComponentsCallback( fltExport->GetNumberOfComponentsCallback() );
  fltImport->SetPropagateUpdateExtentCallback( fltExport->GetPropagateUpdateExtentCallback() );
  fltImport->SetUpdateDataCallback( fltExport->GetUpdateDataCallback() );
  fltImport->SetDataExtentCallback( fltExport->GetDataExtentCallback() );
  fltImport->SetBufferPointerCallback( fltExport->GetBufferPointerCallback() );
  fltImport->SetCallbackUserData( fltExport->GetCallbackUserData() );
}

class UnaryFunctorBinaryToFloat
{
public:
  UnaryFunctorBinaryToFloat()
  {
    m_InsideValue = 1.0f;
  }

  void SetInvertImage(bool invert)
  {
    m_InsideValue = invert ? -1.0f : 1.0f;
  }

  inline float operator()(short in)
  {
    return in == 0 ? -m_InsideValue : m_InsideValue;
  }

  inline bool operator !=(const UnaryFunctorBinaryToFloat & otro) const
  {
    return this->m_InsideValue != otro.m_InsideValue;
  }

private:
  float m_InsideValue;
};

template <class TImage>
class BinaryImageToMeshFilter : public itk::ProcessObject
{
public:
  typedef BinaryImageToMeshFilter       Self;
  typedef itk::ProcessObject            Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;
  typedef itk::Image<float, 3>          FloatImageType;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Image dimension. */
  itkStaticConstMacro(ImageDimension, unsigned int, TImage::ImageDimension);

  /** Get the result mesh */
  vtkPolyData * GetMesh()
  {
    return fltTriangle->GetOutput();
  }

  /** Get the intermediate antialiased image */
  FloatImageType * GetAntiAliasImage()
  {
    return fltAlias->GetOutput();
  }

  /** Whether to invert the binary image */
  itkSetMacro(InvertInput, bool);
  itkGetMacro(InvertInput, bool);

  /** Whether to invert the binary image */
  itkSetMacro(ResampleScaleFactor, float);
  itkGetMacro(ResampleScaleFactor, float);

  /** Whether to decimate the mesh and how much, 0 for none*/
  itkSetMacro(DecimateFactor, double);
  itkGetMacro(DecimateFactor, double);

  /** Smoothing iterations, or 0 for none */
  itkSetMacro(SmoothingIterations, int);
  itkGetMacro(SmoothingIterations, int);

  /** Set the input */
  using Superclass::SetInput;
  virtual void SetInput(TImage *image)
  {
    this->SetNthInput(0, image);
  }

  /** Update method (why?) */
  void Update()
  {
    this->GenerateData();
  }

  /** Set the anti-aliasing quality parameter */
  void SetAntiAliasMaxRMSError(double value)
  {
    fltAlias->SetMaximumRMSError(value);
  }

  /** Get the 'distance image' based on anti-aliasing the binary image */
  FloatImageType * GetDistanceImage()
  {
    return fltAlias->GetOutput();
  }

  /** Get the floating point 'resampled' image, if resampling was enabled */
  FloatImageType * GetResampledImage()
  {
    if( m_ResampleScaleFactor != 1.0f )
      {
      return fltResample->GetOutput();
      }
    else
      {
      return fltToFloat->GetOutput();
      }
  }

  void PrintMeshStatistics(vtkPolyData *mesh)
  {
    vector<unsigned int> cellHist(100, 0);
    for( vtkIdType i = 0; i < mesh->GetNumberOfCells(); i++ )
      {
      cellHist[mesh->GetCellType(i)]++;
      }

    cout << "        mesh has " << mesh->GetNumberOfPoints() << " points." << endl;
    cout << "        mesh has " << mesh->GetNumberOfCells() << " cells. " << endl;
    cout << "        mesh has " << cellHist[VTK_VERTEX] << " vtk_vertex" << endl;
    cout << "        mesh has " << cellHist[VTK_LINE] << " vtk_line" << endl;
    cout << "        mesh has " << cellHist[VTK_POLY_LINE] << " vtk_poly_line" << endl;
    cout << "        mesh has " << cellHist[VTK_TRIANGLE] << " vtk_triangle" << endl;
    cout << "        mesh has " << cellHist[VTK_TRIANGLE_STRIP] << " vtk_triangle_strip" << endl;
  }

protected:
  BinaryImageToMeshFilter()
  {
    // Set the cardinality of the filter
    this->SetNumberOfIndexedInputs(1);
    this->SetNumberOfIndexedOutputs(1);

    // Begin with the well-connectedness filter
    // fltTopology = TopologyFilter::New();

    // Create the converter to float
    fltToFloat = ToFloatFilter::New();
    //    fltToFloat->SetInput(this->GetInput());//fltTopology->GetOutput());
    typename FloatImageType::Pointer imgPipeEnd = fltToFloat->GetOutput();

    // Initialize the interpolation function
    fnInterpolate = ResampleFunction::New();

    // Create a resampling image filter
    fltResample = ResampleFilter::New();
    fltResample->SetInput(imgPipeEnd);
    fltResample->SetTransform(itk::IdentityTransform<double, 3>::New() );
    fltResample->SetInterpolator(fnInterpolate);
    imgPipeEnd = fltResample->GetOutput();

    // Create an anti-aliasing image filter
    fltAlias = AAFilter::New();
    fltAlias->SetMaximumRMSError(0.024);
    fltAlias->SetInput(imgPipeEnd);
    imgPipeEnd = fltAlias->GetOutput();

    // Cast the image to VTK
    fltExport = ExportFilter::New();
    fltImport = vtkImageImport::New();
    fltExport->SetInput(imgPipeEnd);
    ConnectITKToVTK(fltExport.GetPointer(), fltImport);

    // Compute marching cubes
    vtkImageData *importPipeEnd = fltImport->GetOutput();
    fltMarching = vtkImageMarchingCubes::New();
    fltMarching->SetInputData(importPipeEnd);
    fltMarching->ComputeScalarsOff();
    fltMarching->ComputeGradientsOff();
    fltMarching->SetNumberOfContours(1);
    fltMarching->SetValue(0, 0.0f);
    vtkPolyData *meshPipeEnd = fltMarching->GetOutput();

    // Keep the largest connected component
    fltConnect = vtkPolyDataConnectivityFilter::New();
    fltConnect->SetInputData(meshPipeEnd);
    fltConnect->SetExtractionModeToLargestRegion();
    meshPipeEnd = fltMarching->GetOutput();

    fltClean = vtkCleanPolyData::New();
    bool doclean = false;
    if ( doclean ) 
      {
      // Clean up the data
      fltClean->SetInputData(meshPipeEnd);
      meshPipeEnd = fltClean->GetOutput();
      // Decimate the data
      fltDecimate = vtkDecimatePro::New();
      fltDecimate->SetInputData(meshPipeEnd);
      fltDecimate->PreserveTopologyOn();
      meshPipeEnd = fltDecimate->GetOutput();
      }

    // Smooth the data, keeping it on the contour
    vtkSmartPointer<vtkSmoothPolyDataFilter> smoothFilter =
      vtkSmartPointer<vtkSmoothPolyDataFilter>::New();
    smoothFilter->SetInputData(meshPipeEnd);
    smoothFilter->SetNumberOfIterations(5);
    meshPipeEnd = smoothFilter->GetOutput();

    // Compute triangle strips for faster display
    fltTriangle = vtkTriangleFilter::New();
    fltTriangle->SetInputData(meshPipeEnd);
    meshPipeEnd = fltTriangle->GetOutput();

    // Set up progress
    typedef itk::MemberCommand<Self> CommandType;
    typename CommandType::Pointer cmd = CommandType::New();
    cmd->SetCallbackFunction(this, &Self::ProgressCommand);

    // Add progress to the two slow filters
    fltResample->AddObserver(itk::ProgressEvent(), cmd);
    fltAlias->AddObserver(itk::ProgressEvent(), cmd);

    // Invert - NO
    m_InvertInput = false;

    // Resample - NO
    m_ResampleScaleFactor = 1.0f;

    // Decimate - NO
    m_DecimateFactor = 0.0f;
  }

  ~BinaryImageToMeshFilter()
  {
    // CLean up
    fltMarching->Delete();
    fltConnect->Delete();
    fltImport->Delete();
    fltTriangle->Delete();
    fltClean->Delete();
    fltDecimate->Delete();
    fltSmoothMesh->Delete();
  }

  /** Generate Data */
  virtual void GenerateData( void )
  {
    // Run the computation
    cout << "Computing mesh from binary image" << endl;
    // Get the input and output pointers
    typename TImage::ConstPointer inputImage =
      reinterpret_cast<TImage *>(this->GetInput(0) );

    // Pass the input to the topology filter
    // fltTopology->SetInputData(inputImage);

    // Compute the max/min of the image to set fore/back
    typedef itk::MinimumMaximumImageCalculator<TImage> CalcType;
    typename CalcType::Pointer calc = CalcType::New();
    calc->SetImage(inputImage);
    calc->Compute();

    // Set the background and foreground in the topology filter
    // fltTopology->SetBackgroundValue(calc->GetMinimum());
    // fltTopology->SetForegroundValue(calc->GetMaximum());
    // fltTopology->Update();

    // Pass the input to the remapper
    fltToFloat->SetInput(inputImage);

    // Set the inversion if necessary
    m_ToFloatFunctor.SetInvertImage(m_InvertInput);
    fltToFloat->SetFunctor(m_ToFloatFunctor);

    // Convert the image to floats
    fltToFloat->Update();

    // Peform resampling only if necessary
    if( m_ResampleScaleFactor != 1.0 )
      {
      // Include the filter in the pipeline
      fltAlias->SetInput(fltResample->GetOutput() );

      // Set the size parameter
      FloatImageType::SizeType szOutput =
        inputImage->GetBufferedRegion().GetSize();
      szOutput[0] = (unsigned long) (szOutput[0] * m_ResampleScaleFactor);
      szOutput[1] = (unsigned long) (szOutput[1] * m_ResampleScaleFactor);
      szOutput[2] = (unsigned long) (szOutput[2] * m_ResampleScaleFactor);
      fltResample->SetSize(szOutput);

      // Set the scale and origin
      FloatImageType::SpacingType xSpacing =
        inputImage->GetSpacing();
      xSpacing[0] /= m_ResampleScaleFactor;
      xSpacing[1] /= m_ResampleScaleFactor;
      xSpacing[2] /= m_ResampleScaleFactor;
      fltResample->SetOutputSpacing(xSpacing);
      fltResample->SetOutputOrigin(inputImage->GetOrigin() );

      // Compute the resampling
      cout << "   resampling the image " << endl;
      fltResample->Update();
      cout << endl;
      }
    else
      {
      // Exclude the filter from the pipeline
      fltAlias->SetInput(fltToFloat->GetOutput() );
      }

    // Run the filters
    if( fltAlias->GetMaximumRMSError() > 0.0 )
      {
      cout << "   anti-aliasing the image " << endl;
      fltAlias->Update();
      fltExport->SetInput(fltAlias->GetOutput() );
      }
    else
      {
      fltExport->SetInput(fltAlias->GetInput() );
      }
    bool verbose = true;
    if( verbose )
      {
      cout << endl << "   converting image to VTK" << endl;
      }
    fltImport->Update();

    if( verbose )
      {
      cout << "   running marching cubes algorithm" << endl;
      }
    fltMarching->Update();

    if( verbose )
      {
      cout << "      mesh has "
           << fltMarching->GetOutput()->GetNumberOfCells() << " cells and "
           << fltMarching->GetOutput()->GetNumberOfPoints() << " points. " << endl;
      }

    if( verbose )
      {
      cout << "   extracting the largest component" << endl;
      }
    fltConnect->Update();

    if( verbose )
      {
      cout << "      mesh has "
           << fltConnect->GetOutput()->GetNumberOfCells() << " cells and "
           << fltConnect->GetOutput()->GetNumberOfPoints() << " points. " << endl;
      }

    bool doclean = false;
    if ( doclean ) 
      {
      if (verbose) cout << "   cleaning the mesh " << endl;
      fltClean->Update();
      if (verbose) cout << "  after clean step mesh uses " << m_DecimateFactor << " decimation " 
		      << fltClean->GetOutput()->GetNumberOfCells() << " cells and "
		      << fltClean->GetOutput()->GetNumberOfPoints() << " points. " << endl;
      }

    std::cout << "  to decimation with factor " <<  m_DecimateFactor << std::endl;
    // If decimation is on, run it
    if( m_DecimateFactor > 0.0  )
      {
      if( verbose )
        {
        cout << "   decimating the mesh by factor of " << m_DecimateFactor << endl;
        }
      fltDecimate->SetTargetReduction(m_DecimateFactor);
      fltDecimate->SetInputData(fltConnect->GetOutput());
      fltDecimate->Update();
      fltTriangle->SetInputData(fltDecimate->GetOutput() );
      //      if (verbose) cout << "      mesh has "
      // << fltClean->GetOutput()->GetNumberOfCells() << " cells and "
      //  << fltClean->GetOutput()->GetNumberOfPoints() << " points. " << endl;
      }
    else
      {
      fltTriangle->SetInputData(fltConnect->GetOutput());
      }

    if( verbose )
      {
      cout << "   converting mesh to triangles" << endl;
      }
    fltTriangle->Update();
    m_Result = fltTriangle->GetOutput();

    if( verbose )
      {
      cout << "      mesh has "
           <<  m_Result->GetNumberOfCells() << " cells and "
           <<  m_Result->GetNumberOfPoints() << " points. " << endl;
      }

    // If smoothing is on, run it
    if( m_SmoothingIterations > 0  )
      {
      if( verbose )
        {
        cout << "   smoothing the mesh " << m_SmoothingIterations  << endl;
        }
      fltSmoothMesh->SetNumberOfIterations(m_SmoothingIterations);
      fltSmoothMesh->SetInputData(m_Result);
      //      fltSmoothMesh->SetInputConnection(m_Result); // BA FIXME
      fltSmoothMesh->Update();
      m_Result = fltSmoothMesh->GetOutput();
      std::cout << " Done " << std::endl;
      }
  }

private:
  typedef itk::ImageRegionIterator<TImage>      IteratorType;
  typedef itk::ImageRegionConstIterator<TImage> ConstIteratorType;

  // Topology correction filter
  // typedef itk::BinaryWellComposed3DImageFilter<TImage> TopologyFilter;

  // Functor for remapping to float
  UnaryFunctorBinaryToFloat m_ToFloatFunctor;

  // Filter to remap image to floating point
  typedef itk::UnaryFunctorImageFilter<
      TImage, FloatImageType, UnaryFunctorBinaryToFloat> ToFloatFilter;

  // Windowed sinc for resampling
  typedef itk::Function::WelchWindowFunction<4> WindowFunction;
  typedef itk::NearestNeighborInterpolateImageFunction<
      FloatImageType, double> ResampleFunction;

  // Filter to resample image
  typedef itk::ResampleImageFilter<FloatImageType, FloatImageType> ResampleFilter;

  // Antialiasing filter
  typedef itk::AntiAliasBinaryImageFilter<FloatImageType, FloatImageType> AAFilter;

  // Export to VTK filter
  typedef itk::VTKImageExport<FloatImageType> ExportFilter;

  // typename TopologyFilter::Pointer fltTopology;
  typename AAFilter::Pointer fltAlias;
  typename ExportFilter::Pointer fltExport;
  typename ToFloatFilter::Pointer fltToFloat;
  typename ResampleFilter::Pointer fltResample;
  typename ResampleFunction::Pointer fnInterpolate;

  vtkImageImport *               fltImport;
  vtkImageMarchingCubes *        fltMarching;
  vtkPolyDataConnectivityFilter *fltConnect;
  vtkCleanPolyData *             fltClean;
  vtkTriangleFilter *            fltTriangle;
  vtkDecimatePro *               fltDecimate;
  vtkSmoothPolyDataFilter *      fltSmoothMesh;

  bool   m_InvertInput;
  float  m_ResampleScaleFactor;
  double m_DecimateFactor;
  int    m_SmoothingIterations;

  vtkPolyData *m_Result;

  void ProgressCommand(itk::Object *source, const itk::EventObject & /*evt*/)
  {
    // Get the elapsed progress
    itk::ProcessObject *po = reinterpret_cast<ProcessObject *>(source);
    float               progress = po->GetProgress();

    cout << setprecision(4) << (100 * progress) << "  " << flush;
  }
};

#endif