File: itkVTKImageIO2.cxx

package info (click to toggle)
insighttoolkit 3.20.1%2Bgit20120521-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 80,652 kB
  • sloc: cpp: 458,133; ansic: 196,223; fortran: 28,000; python: 3,839; tcl: 1,811; sh: 1,184; java: 583; makefile: 430; csh: 220; perl: 193; xml: 20
file content (704 lines) | stat: -rw-r--r-- 18,967 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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkVTKImageIO2.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     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.

=========================================================================*/

#include "itkVTKImageIO2.h"
#include "itkByteSwapper.h"

#include <itksys/ios/sstream>
#include <itksys/SystemTools.hxx>

#include <stdio.h>
#include <string.h>

namespace itk
{

VTKImageIO2::VTKImageIO2()
{
  this->SetNumberOfDimensions(2);
  m_ByteOrder = LittleEndian;
  m_FileType = Binary;
  m_HeaderSize = 0;

  this->AddSupportedReadExtension(".vtk");

  this->AddSupportedWriteExtension(".vtk");
}

VTKImageIO2::~VTKImageIO2()
{
}


bool VTKImageIO2::CanReadFile(const char* filename)
{
  std::ifstream file;
  char buffer[256];
  std::string fname(filename);

  if ( fname.find(".vtk") >= fname.length() )
    {
    return false;
    }

  try
    {
    this->OpenFileForReading(file, filename);
    }
  catch (... )
    {
    return false;
    }

  // Check to see if its a vtk structured points file
  file.getline(buffer,255);
  file.getline(buffer,255);
  file.getline(buffer,255);
  file.getline(buffer,255);

  fname = buffer;

  if ( fname.find("STRUCTURED_POINTS") < fname.length() ||
       fname.find("structured_points") < fname.length() )
    {
    return true;
    }
  else
    {
    return false;
    }
}

void VTKImageIO2::SetPixelTypeFromString( const std::string & pixelType)
{
  if ( pixelType.find("float") < pixelType.length() )
    {
    SetComponentType(FLOAT);
    }
  else if ( pixelType.find("double") < pixelType.length() )
    {
    SetComponentType(DOUBLE);
    }
  else if ( pixelType.find("unsigned_char") < pixelType.length() )
    {
    SetComponentType(UCHAR);
    }
  else if ( pixelType.find("char") < pixelType.length() )
    {
    SetComponentType(CHAR);
    }
  else if ( pixelType.find("unsigned_short") < pixelType.length() )
    {
    SetComponentType(USHORT);
    }
  else if ( pixelType.find("short") < pixelType.length() )
    {
    SetComponentType(SHORT);
    }
  else if ( pixelType.find("unsigned_int") < pixelType.length() )
    {
    SetComponentType(UINT);
    }
  else if ( pixelType.find("int") < pixelType.length() )
    {
    SetComponentType(INT);
    }
  else if ( pixelType.find("unsigned_long") < pixelType.length() )
    {
    SetComponentType(ULONG);
    }
  else if ( pixelType.find("long") < pixelType.length() )
    {
    SetComponentType(LONG);
    }
  else
    {
    itkExceptionMacro(<<"Unrecognized type");
    }

}

void VTKImageIO2::InternalReadImageInformation(std::ifstream& file)
{
  char line[255];
  std::string text;

  this->OpenFileForReading(file, m_FileName.c_str());

  file.getline(line,255);
  file.getline(line,255);
  file.getline(line,255);
  text = line;
  if ( text.find("ASCII") < text.length() ||
       text.find("ascii") < text.length() )
    {
    this->SetFileTypeToASCII();
    }
  else if ( text.find("BINARY") < text.length() ||
            text.find("binary") < text.length() )
    {
    this->SetFileTypeToBinary();
    }
  else
    {
    itkExceptionMacro(<< "Unrecognized type");
    }
  file.getline(line,255);
  text = line;
  if ( text.find("STRUCTURED_POINTS") >= text.length() &&
       text.find("structured_points") >= text.length() )
    {
    itkExceptionMacro(<< "Not structured points, can't read");
    }


  file.getline(line,255);
  text = line;

  // set values in case we don't find them
  this->SetNumberOfDimensions(3);
  this->SetSpacing( 0, 1.0 );
  this->SetSpacing( 1, 1.0 );
  this->SetSpacing( 2, 1.0 );
  this->SetOrigin( 0, 0.0 );
  this->SetOrigin( 1, 0.0 );
  this->SetOrigin( 2, 0.0 );

  if ( text.find("DIMENSIONS") < text.length() ||
       text.find("dimensions") < text.length() )
    {
    unsigned int dims[3];
    sscanf(line, "%*s %d %d %d", dims, dims+1, dims+2);
    if ( dims[1] <= 1 && dims[2] <= 1 )
      {
      this->SetNumberOfDimensions(2);
      }
    if ( dims[2] <= 1 )
      {
      this->SetNumberOfDimensions(2);
      }
    else
      {
      this->SetNumberOfDimensions(3);
      }
    for ( unsigned int i=0; i < this->GetNumberOfDimensions(); i++ )
      {
      this->SetDimensions( i, dims[i] );
      }
    }
  else
    {
    itkExceptionMacro(<<"No dimensions defined");
    }

  for ( bool readScalars=false; !readScalars; )
    {
    file.getline(line,255);
    text = line;

    if ( text.find("SPACING") < text.length() ||
         text.find("spacing") < text.length() ||
         text.find("ASPECT_RATIO") < text.length() ||
         text.find("aspect_ratio") < text.length() )
      {
      double spacing[3];
      sscanf(line, "%*s %lf %lf %lf", spacing, spacing+1, spacing+2);
      for ( unsigned int i=0; i < m_NumberOfDimensions; i++ )
        {
        this->SetSpacing( i, spacing[i] );
        }
      }

    else if ( text.find("ORIGIN") < text.length() ||
              text.find("origin") < text.length() )
      {
      double origin[3];
      sscanf(line, "%*s %lf %lf %lf", origin, origin+1, origin+2);
      for ( unsigned int i=0; i < m_NumberOfDimensions; i++ )
        {
        this->SetOrigin( i, origin[i] );
        }
      }

    else if ( text.find("VECTOR") < text.length() ||
              text.find("vector") < text.length() )
      {
      readScalars = true;

      this->SetNumberOfComponents(3);
      this->SetPixelType(VECTOR);
      char pixelType[256];
      sscanf(line, "%*s %*s %s", pixelType);
      text = pixelType;

      this->SetPixelTypeFromString(text);

      }

    else if ( text.find("COLOR_SCALARS") < text.length() ||
              text.find("color_scalars") < text.length() )
      {
      readScalars = true;

      int numComp = 1;
      sscanf(line, "%*s %*s %d", &numComp);
      if (numComp == 1)
        {
        this->SetPixelType(SCALAR);
        }
      else if (numComp == 3 )
        {
        this->SetPixelType( RGB );
        }
      else if ( numComp == 4 )
        {
        this->SetPixelType( RGBA );
        }
      else
        {
        SetPixelType(VECTOR);
        }
      if ( this->GetFileType() == ASCII )
        {
        this->SetNumberOfComponents( numComp );
        this->SetComponentType( FLOAT );
        }
      else
        {
        this->SetNumberOfComponents( numComp );
        this->SetComponentType( UCHAR );
        }
      }

    else if ( text.find("SCALARS") < text.length() ||
              text.find("scalars") < text.length() )
      {
      readScalars = true;

      char pixelType[256];
      int numComp = 1;
      // numComp is optional
      sscanf(line, "%*s %*s %s %d", pixelType, &numComp);
      text = pixelType;
      if (numComp == 1)
        {
        this->SetPixelType(SCALAR);
        }
      else
        {
        this->SetPixelType(VECTOR);
        }
      this->SetPixelTypeFromString(text);
      this->SetNumberOfComponents(numComp);


      // maybe "LOOKUP_TABLE default"
      std::streampos pos = file.tellg();
      file.getline(line,255);
      text = line;
      if ( !(text.find("LOOKUP_TABLE") < text.length() ||
             text.find("lookup_table") < text.length() ) )
        {
        // it was data and not table
        file.seekg( pos );
        }

      }//found scalars

    if ( !file.good() )
      {
      itkExceptionMacro(<<"Error reading header");
      }
    }

  // set the header size based on how much we just read
  this->m_HeaderSize = static_cast<SizeType>( file.tellg() );

}


void VTKImageIO2::ReadHeaderSize(std::ifstream& file)
{
  char line[255];
  std::string text;

  this->OpenFileForReading(file, m_FileName.c_str());

  file.getline(line,255); // HEADER
  file.getline(line,255); // TITLE
  file.getline(line,255); // DATA TYPE
  file.getline(line,255); // GEOMEETRY/TOPOLOGY TYPE

  file.getline(line,255); // DIMENSIONS

  for ( bool readScalars=false; !readScalars; )
    {
    file.getline(line,255); // SPACING|ORIGIN|COLOR_SCALARS|SCALARS|VECTOR
    text = line;

    if ( text.find("SCALARS") < text.length() ||
         text.find("scalars") < text.length() ||
         text.find("VECTOR") < text.length() ||
         text.find("vector") < text.length() ||
         text.find("COLOR_SCALARS") < text.length() ||
         text.find("color_scalars") < text.length() )
      {
      readScalars = true;

      // maybe "LOOKUP_TABLE default"
      std::streampos pos = file.tellg();
      file.getline(line,255);
      text = line;
      if ( !(text.find("LOOKUP_TABLE") < text.length() ||
             text.find("lookup_table") < text.length()) )
        {
        // it was data and not table
        file.seekg( pos );
        }
      else
        {
        }
      } //found scalars

    }

  if ( file.fail() )
    {
    itkExceptionMacro(<<"Failed reading header information");
    }

  // set the header size based on how much we just read
  this->m_HeaderSize = static_cast<SizeType>( file.tellg() );

}

void VTKImageIO2::Read(void* buffer)
{
  std::ifstream file;

  if( this->RequestedToStream() )
    {

    itkAssertOrThrowMacro( m_FileType != ASCII, "Can not stream with ASCII type files" );

    // open and stream read
    this->OpenFileForReading(file, this->m_FileName.c_str());

    itkAssertOrThrowMacro( this->GetHeaderSize() != 0, "Header size is unknown when it shouldn't be!");
    this->StreamReadBufferAsBinary(file, buffer);

    }
  else
    {

    // open the file
    this->OpenFileForReading(file, this->m_FileName.c_str());

    itkAssertOrThrowMacro( this->GetHeaderSize() != 0, "Header size is unknown when it shouldn't be!");


    if ( file.fail() )
      {
      itkExceptionMacro(<<"Failed seeking to data position");
      }

    // seek pass the header
    std::streampos dataPos = static_cast<std::streampos>( this->GetHeaderSize() );
    file.seekg( dataPos, std::ios::beg );

    //We are positioned at the data. The data is read depending on whether
    //it is ASCII or binary.
    if ( m_FileType == ASCII )
      {
      this->ReadBufferAsASCII(file, buffer, this->GetComponentType(),
                              this->GetImageSizeInComponents());
      }
    else
      {
      // read the image
      this->ReadBufferAsBinary( file, buffer, this->GetImageSizeInBytes() );

      int size = this->GetComponentSize();
      switch( size )
        {
        case 1:
          break;
        case 2:
          ByteSwapper<uint16_t>::SwapRangeFromSystemToBigEndian((uint16_t *)buffer, this->GetImageSizeInComponents() );
          break;
        case 4:
          ByteSwapper<uint32_t>::SwapRangeFromSystemToBigEndian((uint32_t *)buffer, this->GetImageSizeInComponents() );
          break;
#ifdef ITK_HAS_INT_64
        case 8:
          ByteSwapper<uint64_t>::SwapRangeFromSystemToBigEndian((uint64_t *)buffer, this->GetImageSizeInComponents() );
          break;
#else
        case 8:
          ByteSwapper<double>::SwapRangeFromSystemToBigEndian((double *)buffer, this->GetImageSizeInComponents() );
          break;
#endif
        default:
          itkExceptionMacro(<< "Unknown component size" << size);
        }
      }
    }

}


void VTKImageIO2::ReadImageInformation()
{
  std::ifstream file;
  this->InternalReadImageInformation(file);
}

bool VTKImageIO2::CanWriteFile( const char* name )
{
  std::string filename = name;
  if ( filename != "" &&
       filename.find(".vtk") < filename.length() )
    {
    return true;
    }
  return false;
}

void VTKImageIO2::WriteImageInformation(const void* itkNotUsed(buffer))
{

  std::ofstream file;
  // this will truncate the file
  this->OpenFileForWriting(file,m_FileName.c_str(), true );

  // Check the image region for proper dimensions, etc.
  unsigned int numDims = this->GetNumberOfDimensions();
  if ( numDims < 1 || numDims > 3 )
    {
    itkExceptionMacro(<<"VTK Writer can only write 1, 2 or 3-dimensional images");
    return;
    }

  // Write the VTK header information
  file << "# vtk DataFile Version 3.0\n";
  file << "VTK File Generated by Insight Segmentation and Registration Toolkit (ITK)\n";

  if ( this->GetFileType() == ASCII )
    {
    file << "ASCII\n";
    }
  else
    {
    file << "BINARY\n";
    }


  file.setf( itksys_ios::ios::scientific,
             itksys_ios::ios::floatfield );

  file.precision(16);

  file.flush();

  // Write characteristics of the data
  file << "DATASET STRUCTURED_POINTS\n";
  file << "DIMENSIONS "
       << this->GetDimensions(0) << " "
       << ((this->GetNumberOfDimensions() > 1) ? this->GetDimensions(1) : 1) << " "
       << ((this->GetNumberOfDimensions() > 2) ? this->GetDimensions(2) : 1) << " "
       << "\n";
  file << "SPACING "
       << this->GetSpacing(0) << " "
       << ((this->GetNumberOfDimensions() > 1) ? this->GetSpacing(1) : 1.0) << " "
       << ((this->GetNumberOfDimensions() > 2) ? this->GetSpacing(2) : 1.0) << " "
       << "\n";
  file << "ORIGIN "
       << this->GetOrigin(0) << " "
       << ((this->GetNumberOfDimensions() > 1) ? this->GetOrigin(1) : 0.0) << " "
       << ((this->GetNumberOfDimensions() > 2) ? this->GetOrigin(2) : 0.0) << " "
       << "\n";

  file << "POINT_DATA " << this->GetImageSizeInPixels() << "\n";

  // NOTE: we don't write out RGB pixel types with ascii due to complication of
  // the required datatypes and the different ranges
  if ( ( (this->GetPixelType() == RGB && this->GetNumberOfComponents() == 3 ) ||
         (this->GetPixelType() == RGBA && this->GetNumberOfComponents() == 4 ) )
       &&
       ( this->GetComponentType() == UCHAR ) &&
       ( this->GetFileType() == Binary )  )
    {
    file << "COLOR_SCALARS color_scalars" << " "
         << this->GetNumberOfComponents() << "\n";
    }
  // Prefer the VECTORS representation when possible:
  else if( this->GetPixelType() == VECTOR && this->GetNumberOfComponents() == 3 )
    {
    file << "VECTORS vectors "
      << this->GetComponentTypeAsString(m_ComponentType) << "\n";
    }
  else
    {
    // According to VTK documentation number of components should in
    // range (1,4):
    // todo this should be asserted or checked ealier!
    file << "SCALARS scalars "
      << this->GetComponentTypeAsString(m_ComponentType) << " "
      << this->GetNumberOfComponents() << "\n"
      << "LOOKUP_TABLE default\n";
    }

  // set the header size based on how much we just wrote
  this->m_HeaderSize = static_cast<SizeType>( file.tellp() );
}

void VTKImageIO2::Write(const void* buffer)
{


  if( this->RequestedToStream() )
    {

    itkAssertOrThrowMacro( m_FileType != ASCII, "Can not stream with ASCII type files" );


    std::ofstream file;

    // we assume that GetActualNumberOfSplitsForWriting is called before
    // this methods and it will remove the file if a new header needs to
    // be written
    if (!itksys::SystemTools::FileExists( m_FileName.c_str() ))
      {

      this->WriteImageInformation( buffer );

      // open and stream write
      this->OpenFileForWriting(file, this->m_FileName.c_str(), false);

      // write one byte at the end of the file to allocate (this is a
      // nifty trick which should not write the entire size of the file
      // just allocate it, if the system supports sparse files)
      std::streampos seekPos = this->GetImageSizeInBytes() + this->GetHeaderSize() - 1;
      file.seekp( seekPos, std::ios::cur );
      file.write("\0", 1);
      file.seekp( 0 );
      }
    else
      {


      // must always recheck the header size incase something has changed
      std::ifstream ifile;
      this->ReadHeaderSize( ifile );

      itkAssertOrThrowMacro( this->GetHeaderSize() != 0, "Header size is unknown when it shouldn't be!");

      // open and stream write
      this->OpenFileForWriting(file, this->m_FileName.c_str(), false);

      }

    this->StreamWriteBufferAsBinary(file, buffer);

    }

  else
    {

    // this will truncate file and write header
    this->WriteImageInformation( buffer );

    std::ofstream file;
    // open the file
    this->OpenFileForWriting(file, this->m_FileName.c_str(), false);

    itkAssertOrThrowMacro( this->GetHeaderSize() != 0, "Header size is unknown when it shouldn't be!");

    // seek pass the header
    std::streampos dataPos = static_cast<std::streampos>( this->GetHeaderSize() );
    file.seekp( dataPos, std::ios::beg );

    if ( file.fail() )
      {
      itkExceptionMacro(<<"Failed seeking to data position");
      }

    // Write the actual pixel data
    if ( m_FileType == ASCII )
      {

      this->WriteBufferAsASCII(file, buffer, this->GetComponentType(),
                               this->GetImageSizeInComponents());
      }
    else //binary
      {
      // the binary data must be written in big endian format
      if ( ! ByteSwapper<uint16_t>::SystemIsBigEndian() )
        {
        // only swap  when needed
        const ImageIOBase::BufferSizeType numbytes =
          static_cast<ImageIOBase::BufferSizeType>( this->GetImageSizeInBytes() );

        char * tempmemory = new char[numbytes];
        memcpy(tempmemory,buffer,numbytes);
        switch(  this->GetComponentSize() )
          {
          case 1:
            break;
          case 2:
            ByteSwapper<uint16_t>::SwapRangeFromSystemToBigEndian((uint16_t *)(tempmemory), static_cast<BufferSizeType>(this->GetImageSizeInComponents()) );
            break;
          case 4:
            ByteSwapper<uint32_t>::SwapRangeFromSystemToBigEndian((uint32_t *)(tempmemory), static_cast<BufferSizeType>(this->GetImageSizeInComponents()) );
            break;
#ifdef ITK_HAS_INT_64
          case 8:
            ByteSwapper<uint64_t>::SwapRangeFromSystemToBigEndian((uint64_t *)(tempmemory), static_cast<BufferSizeType>(this->GetImageSizeInComponents()) );
            break;
#else
          case 8:
            ByteSwapper<double>::SwapRangeFromSystemToBigEndian((double *)(tempmemory), static_cast<BufferSizeType>(this->GetImageSizeInComponents()) );
            break;

#endif
          }

        // write the image
        if (!this->WriteBufferAsBinary( file, tempmemory, this->GetImageSizeInBytes() ))
          {
          itkExceptionMacro(<< "Could not write file: " << m_FileName);
          }
        delete [] tempmemory;
        }
      else
        {
        // write the image
        if (!this->WriteBufferAsBinary( file, buffer, this->GetImageSizeInBytes() ))
          {
          itkExceptionMacro(<< "Could not write file: " << m_FileName);
          }
        }
      }
    }
}

void VTKImageIO2::PrintSelf(std::ostream& os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);
}

} // end namespace itk