File: GuidedNativeImageIO.h

package info (click to toggle)
itksnap 3.6.0-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 22,132 kB
  • sloc: cpp: 91,089; ansic: 1,994; sh: 327; makefile: 16
file content (459 lines) | stat: -rwxr-xr-x 14,992 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
/*=========================================================================

  Program:   ITK-SNAP
  Module:    $RCSfile: GuidedNativeImageIO.h,v $
  Language:  C++
  Date:      $Date: 2010/10/14 16:21:04 $
  Version:   $Revision: 1.6 $
  Copyright (c) 2007 Paul A. Yushkevich
  
  This file is part of ITK-SNAP 

  ITK-SNAP is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
 
  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.

  -----

  Copyright (c) 2003 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. 

=========================================================================*/
#ifndef __GuidedNativeImageIO_h_
#define __GuidedNativeImageIO_h_

#include "Registry.h"
#include "itkSmartPointer.h"
#include "itkImage.h"
#include "itkImageIOBase.h"
#include "itkVectorImage.h"
#include "itkGDCMSeriesFileNames.h"
#include "gdcmTag.h"

  
namespace itk
{
  template<class TPixel, unsigned int VDim> class Image;
  class ImageIOBase;
  class Command;
}


/**
 * \class GuidedNativeImageIO
 * \brief This class performs image IO based on user-supplied parameters such
 * as explicit IO type, and for some types such as raw, the necessary additional
 * information.
 */
class GuidedNativeImageIO : public itk::Object
{
public:

  irisITKObjectMacro(GuidedNativeImageIO, itk::Object)

  enum FileFormat {
    FORMAT_ANALYZE=0,
    FORMAT_DICOM_DIR,       // A directory containing multiple DICOM files
    FORMAT_DICOM_FILE,      // A single DICOM file
    FORMAT_GE4, FORMAT_GE5, FORMAT_GIPL,
    FORMAT_MHA, FORMAT_NIFTI, FORMAT_NRRD, FORMAT_RAW, FORMAT_SIEMENS,
    FORMAT_VOXBO_CUB, FORMAT_VTK, FORMAT_COUNT};

  enum RawPixelType {
    PIXELTYPE_UCHAR=0, PIXELTYPE_CHAR, PIXELTYPE_USHORT, PIXELTYPE_SHORT, 
    PIXELTYPE_UINT, PIXELTYPE_INT, PIXELTYPE_FLOAT, PIXELTYPE_DOUBLE,
    PIXELTYPE_COUNT};

  /**
   * A descriptor of file formats supported in ITK. Describes whether
   * the format can support different needs in SNAP 
   */
  struct FileFormatDescriptor 
  {
    std::string name;
    std::string pattern;
    bool can_write;
    bool can_store_orientation;
    bool can_store_float;
    bool can_store_short;

    bool TestFilename(std::string fname);
  };

  /**
   * Structure describing last parsed DICOM directory - basically
   * a map from SeriesId to MetaData registry and a list of files
   * that is not ordered until the image is actually loaded.
   */
  struct DicomDirectoryParseResult
  {
    typedef std::vector<std::string> FileListType;

    // Structure describing one DICOM series
    struct DicomSeriesInfo {
      Registry MetaData;
      FileListType FileList;
    };

    typedef std::map<std::string, DicomSeriesInfo> SeriesMapType;

    // Directory that was parsed
    std::string Directory;

    // Filenames of the images for each series ID
    SeriesMapType SeriesMap;

    void Reset();
  };


  // Image type. This is only for 3D images.
  typedef itk::ImageIOBase IOBase;
  typedef itk::SmartPointer<IOBase> IOBasePointer;

  typedef itk::ImageBase<3> ImageBase;
  typedef itk::SmartPointer<ImageBase> ImageBasePointer;

  /**
   * This method loads an image from the given filename. A registry can be 
   * supplied to assist the loading. The registry specifies the desired IO
   * type, and for special types, such as Raw it can provide the parameters
   * such as header size and image dimensions. The image is read in native
   * format and stored inside of this object. In order to cast the image to 
   * the format of interest, the user must cast the image to one of the 
   * desired formats.
   */
  void ReadNativeImage(const char *FileName, Registry &folder);

  void ReadNativeImageHeader(const char *FileName, Registry &folder);

  void ReadNativeImageData();

  /**
   * Get the number of components in the native image read by ReadNativeImage.
   */
  size_t GetNumberOfComponentsInNativeImage() const;

  /**
    Access the IO header stored in the IO object. This is only temporarily
    available between calls to ReadNativeImageHeader() and ReadNativeImageData().
    The purpose is to allow users to check the validity of the header before
    actually loading the data completely.
    */
  itk::ImageIOBase *GetIOBase()
    { return m_IOBase; }

  /**
   * Get the component type in the native image
   */
  itk::ImageIOBase::IOComponentType GetComponentTypeInNativeImage() const
    { return m_NativeType; }

  itk::ImageIOBase::ByteOrder GetByteOrderInNativeImage() const
    { return m_NativeByteOrder; }

  std::string GetComponentTypeAsStringInNativeImage() const
    { return m_NativeTypeString; }

  std::string GetFileNameOfNativeImage() const
    { return m_NativeFileName; }

  unsigned long GetFileSizeOfNativeImage() const
    { return m_NativeSizeInBytes; }

  std::string GetNicknameOfNativeImage() const
    { return m_NativeNickname; }

  Vector3ui GetDimensionsOfNativeImage() const
    { return m_NativeDimensions; }

  /**
   * This method returns the image internally stored in this object. This is
   * a pointer to an itk::VectorImage of some native format. Use one of the
   * Cast objects to cast it to an image of the type you want
   */
  itk::ImageBase<3> *GetNativeImage() const
    { return m_NativeImage; }

  /**
   * Has a native image been loaded?
   */
  bool IsNativeImageLoaded() const
    { return m_NativeImage.IsNotNull(); }

  /**
   * Discard the native image. Use this once you've cast the native image to 
   * the format of interest.
   */
  void DeallocateNativeImage()
    { m_IOBase = NULL; m_NativeImage = NULL; }

  /** 
   * Get RAI code for an image. If there is nothing in the registry, this will
   * try getting the code from the image header. If there is no way to get the
   * image code, this will return an empty string
   */
  // std::string GetRAICode(ImageType *image, Registry &folder);

  /** 
   * Save an image using the Registry folder to specify parameters. This method
   * is templated over the image type.
   */
  template<class TImageType>
    void SaveImage(const char *FileName, Registry &folder, TImageType *image);

  /** Parse registry to get file format */
  static FileFormat GetFileFormat(Registry &folder, FileFormat dflt = FORMAT_COUNT);

  /** Set the file format in a registry */
  static void SetFileFormat(Registry &folder, FileFormat format);

  /** Get format descriptor for a format */
  static FileFormatDescriptor GetFileFormatDescriptor(FileFormat fmt)
    { return m_FileFormatDescrictorArray[fmt]; }

  /**
    Determine file format for a filename. This method can optionally try to
    open the file and scan the magic number, for the formats that are known
    */
  static FileFormat GuessFormatForFileName(
      const std::string &string, bool checkMagic);

  /** Parse registry to get pixel type of raw file */
  static RawPixelType GetPixelType(Registry &folder, RawPixelType dflt = PIXELTYPE_COUNT);

  /** Set the file format in a registry */
  static void SetPixelType(Registry &folder, RawPixelType type);

  /** Output for ParseDicomDirectory */
  typedef std::vector<Registry> RegistryArray;

  /**
   * Get series information from a DICOM directory. This will list all the
   * files in the DICOM directory and generate a registry for each series in
   * the directory. The following registry entries are generated for each series:
   *   - SeriesDescription
   *   - Dimensions
   *   - NumberOfImages
   *   - SeriesId
   *   - SeriesFiles (an array with filenames)
   *
   * To obtain the result of the parsing call GetLastDicomParseRegistry()
   */
  void ParseDicomDirectory(
      const std::string &dir, itk::Command *progressCommand = NULL);

  /**
   * Get the result of the last parse operation. This should be safe to
   * call from the callback of progressCommand in ParseDicomDirectory(),
   * and can be done to update a GUI on the fly, as images are being parsed
   */
  itkGetConstReferenceMacro(LastDicomParseResult, DicomDirectoryParseResult)

  /**
   * Create an ImageIO object using a registry folder. Second parameter is
   * true for reading the file, false for writing the file
   */
  void CreateImageIO(const char *fname, Registry &folder, bool read);

  // Get the output of the last operation
  // irisGetMacro(IOBase, itk::ImageIOBase *);    

protected:

  GuidedNativeImageIO();
  virtual ~GuidedNativeImageIO()
    { DeallocateNativeImage(); }

  /** Templated function to create RAW image IO */
  template <typename TRaw> void CreateRawImageIO(Registry &folder);

  /** Templated function that reads a scalar image in its native datatype */
  template <typename TScalar> void DoReadNative(const char *fname, Registry &folder);

  /** 
   This is a vector image in native format. It stores the data read from the
   image file. The user must cast it to a desired type to use it. Once it has
   been cast, the native image becomes unusable because casting is done inplace
   so the buffer initially allocated for the native image may be resized and
   overridden.
   */
  ImageBasePointer m_NativeImage;

  // The IO base used to read the files
  IOBasePointer m_IOBase;

  // DICOM directory last processed by ParseDicomSeries
  DicomDirectoryParseResult m_LastDicomParseResult;

  // This information is copied from IOBase in order to delete IOBase at the 
  // earliest possible point, so as to conserve memory
  IOBase::IOComponentType m_NativeType;
  size_t m_NativeComponents;
  unsigned long m_NativeSizeInBytes;
  std::string m_NativeTypeString, m_NativeFileName;
  std::string m_NativeNickname;
  IOBase::ByteOrder m_NativeByteOrder;
  Vector3ui m_NativeDimensions;

  // Copy of the registry passed in when reading header
  Registry m_Hints;

  // The file format
  FileFormat m_FileFormat;

  // List of filenames for DICOM
  std::vector<std::string> m_DICOMFiles;

  /** Registry mappings for these enums */
  static bool m_StaticDataInitialized;
  static RegistryEnumMap<FileFormat> m_EnumFileFormat;
  static RegistryEnumMap<RawPixelType> m_EnumRawPixelType;

  // File format descriptors
  static const FileFormatDescriptor m_FileFormatDescrictorArray[];

  static const gdcm::Tag m_tagRows;
  static const gdcm::Tag m_tagCols;
  static const gdcm::Tag m_tagDesc;
  static const gdcm::Tag m_tagSeriesInstanceUID;
  static const gdcm::Tag m_tagSeriesNumber;
  static const gdcm::Tag m_tagAcquisitionNumber;
  static const gdcm::Tag m_tagInstanceNumber;
  static const gdcm::Tag m_tagSequenceName;
  static const gdcm::Tag m_tagSliceThickness;

};


/**
 * \class RescaleNativeImageToIntegralType
 * \brief An adapter class that rescales a native-format image from 
 * GuidedNativeImageIO to user-specified scalar type
 */
template<class TOutputImage>
class RescaleNativeImageToIntegralType
{
public:
  RescaleNativeImageToIntegralType() {}
  virtual ~RescaleNativeImageToIntegralType() {}

  typedef TOutputImage                                         OutputImageType;
  typedef typename TOutputImage::PixelType                     OutputPixelType;
  typedef itk::ImageBase<3>                                    NativeImageType;

  // Constructor, takes pointer to native image
  OutputImageType *operator()(GuidedNativeImageIO *nativeIO);

  // Get the scale factor to map from scalar to native
  irisGetMacro(NativeScale, double)

  // Get the shift to map from scalar to native
  irisGetMacro(NativeShift, double)

private:
  typename OutputImageType::Pointer m_Output;
  double m_NativeScale, m_NativeShift;

  // Method that does the casting
  template<typename TNative> void DoCast(itk::ImageBase<3> *native);
};

template<class TPixel> class TrivialCastFunctor
{
public:
  typedef TPixel PixelType;
  template<class TNative> void operator()(TNative *src, TPixel *trg)
    { *trg = static_cast<TPixel>(*src); }
};


/**
 * \class CastNativeImageBase
 * \brief An adapter class that casts a native-format image from 
 * GuidedNativeImageIO to an output image type. The actual casting
 * is done using the functor TCastFunctor. Use derived classes.
 */
template<class TOutputImage,
         class TCastFunctor =
           TrivialCastFunctor<typename TOutputImage::InternalPixelType> >
class CastNativeImage
{
public:
  typedef TOutputImage                                         OutputImageType;
  typedef RescaleNativeImageToIntegralType<OutputImageType>       RescalerType;
  typedef typename RescalerType::NativeImageType               NativeImageType;
  typedef typename OutputImageType::PixelType                  OutputPixelType;
  typedef typename OutputImageType::InternalPixelType      OutputComponentType;

  // Constructor, takes pointer to native image
  OutputImageType *operator()(GuidedNativeImageIO *nativeIO);

  // Set the functor
  void SetFunctor(TCastFunctor functor) 
    { m_Functor = functor; }

private:
  typename OutputImageType::Pointer m_Output;
  TCastFunctor m_Functor;

  // Method that does the casting
  template<typename TNative> void DoCast(itk::ImageBase<3> *native);

  friend class RescaleNativeImageToIntegralType<OutputImageType>;
};

// Functor used for scalar to scalar casting
template<class TPixel> class CastToScalarFunctor
{
public:
  template<class TNative> void operator()(TNative *src, TPixel *trg)
    { *trg = (TPixel) *src; }
  size_t GetNumberOfDimensions() { return 1; }
};

// Functor used for scalar to array casting
template<class TPixel, unsigned int VDim> class CastToArrayFunctor
{
public:
  template<class TNative> void operator()(TNative *src, TPixel *trg)
    { for(unsigned int i = 0; i < VDim; i++) (*trg)[i] = (typename TPixel::ComponentType) src[i]; }
  size_t GetNumberOfDimensions() { return VDim; }
};

/**
 * \class CastNativeImageToRGB
 * \brief An adapter class that casts a native-format image from 
 * GuidedNativeImageIO to an RGB image
 */
/*
template<typename TRGBPixel>
class CastNativeImageToRGB : 
  public CastNativeImageBase<TRGBPixel, CastToArrayFunctor<TRGBPixel, 3> > {};
*/

/**
 * \class CastNativeImageToScalar
 * \brief An adapter class that casts a native-format image from 
 * GuidedNativeImageIO to a scalar image of given type
 */
/*
template<typename TPixel>
class CastNativeImageToScalar : 
  public CastNativeImageBase<TPixel, CastToScalarFunctor<TPixel> > {};
*/

#endif