]> Creatis software - gdcm.git/blob - vtk/vtkGdcmReader.cxx
upgrades for 4DSplitter
[gdcm.git] / vtk / vtkGdcmReader.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: vtkGdcmReader.cxx,v $
5   Language:  C++
6   Date:      $Date: 2011/03/29 07:36:02 $
7   Version:   $Revision: 1.99 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18                                                                                 
19 //-----------------------------------------------------------------------------
20 // //////////////////////////////////////////////////////////////
21 //
22 //===>  Many users expect from vtkGdcmReader it 'orders' the images
23 //     (that's the job of GDCM_NAME_SPACE::SerieHelper ...)
24 //     When user *knows* the files with same Serie UID 
25 //        have same sizes, same 'pixel' type, same color convention, ...
26 //     the right way to proceed is as follow :
27 //
28 //      GDCM_NAME_SPACE::SerieHelper *sh= new GDCM_NAME_SPACE::SerieHelper();
29 //      // if user wants *not* to load some parts of the file headers
30 //      sh->SetLoadMode(loadMode);
31 //
32 //      // if user wants *not* to load some files 
33 //      sh->AddRestriction(group, element, value, operator);
34 //      sh->AddRestriction( ...
35 //      sh->SetDirectory(directoryWithImages);
36 //
37 //      // if user wants to sort reverse order
38 //      sh->SetSortOrderToReverse(); 
39 //
40 //      // here, we suppose only the first 'Serie' is of interest
41 //      // it's up to the user to decide !
42 //      GDCM_NAME_SPACE::FileList *l = sh->GetFirstSingleSerieUIDFileSet();
43 //
44 //      // if user is doesn't trust too much the files with same Serie UID 
45 //      if ( !sh->IsCoherent(l) )
46 //         return; // not same sizes, same 'pixel' type -> stop
47 //
48 //      // WARNING : all  that follows works only with 'bona fide' Series
49 //      // (In some Series; there are more than one 'orientation'
50 //      // Don't expected to build a 'volume' with that!
51 //      //
52 //      // -> use sh->SplitOnOrientation(l)
53 //      //  - or sh->SplitOnPosition(l), or SplitOnTagValue(l, gr, el) -
54 //      // depending on what you want to do
55 //      // and iterate on the various 'X Coherent File Sets'
56 //
57 //      // if user *knows* he has to drop the 'duplicates' images
58 //      // (same Position)
59 //      sh->SetDropDuplicatePositions(true);
60 //
61 //      // Sorting the list is mandatory
62 //      // a side effect is to compute ZSpacing for the file set
63 //      sh->OrderFileList(l);        // sort the list
64 //
65 //      vtkGdcmReader *reader = vtkGdcmReader::New();
66 //
67 //      // if user wants to modify pixel order (Mirror, TopDown, 90°Rotate, ...)
68 //      // he has to supply the function that does the job 
69 //      // (a *very* simple example is given in vtkgdcmSerieViewer.cxx)
70 //      reader->SetUserFunction (userSuppliedFunction);
71 //
72 //      // to pass a 'Coherent File List' as produced by GDCM_NAME_SPACE::SerieHelper
73 //      reader->SetCoherentFileList(l); 
74 //      reader->Update();
75 //
76 // WARNING TODO CLEANME 
77 // Actual limitations of this code 
78 //  when a Coherent File List from SerieHelper is not used (bad idea :-(
79 //
80 // //////////////////////////////////////////////////////////////
81
82 #include "gdcmFileHelper.h"
83 #include "gdcmFile.h"
84 #include "gdcmSerieHelper.h" // for ImagePositionPatientOrdering()
85
86 #include "vtkGdcmReader.h"
87 #include "gdcmDebug.h"
88 #include "gdcmCommon.h"
89
90 #include <vtkObjectFactory.h>
91 #include <vtkImageData.h>
92 #include <vtkPointData.h>
93 #include <vtkLookupTable.h>
94
95 vtkCxxRevisionMacro(vtkGdcmReader, "$Revision: 1.99 $")
96 vtkStandardNewMacro(vtkGdcmReader)
97
98 //-----------------------------------------------------------------------------
99 // Constructor / Destructor
100 vtkGdcmReader::vtkGdcmReader()
101 {
102    this->LookupTable = NULL;
103    this->AllowLookupTable = false;
104    //this->AllowLightChecking = false;
105    this->LoadMode = GDCM_NAME_SPACE::LD_ALL; // Load everything (possible values : 
106                                   //  - LD_NOSEQ, 
107                                   //  - LD_NOSHADOW,
108                                   //  - LD_NOSHADOWSEQ)
109    this->CoherentFileList = 0;
110    this->UserFunction     = 0;
111
112    this->OwnFile=true;
113    // this->Execution=false; // For VTK5.0
114    
115    this->KeepOverlays = false;
116    this->FlipY = true; // to keep old behaviour
117 }
118
119 vtkGdcmReader::~vtkGdcmReader()
120 {
121    this->RemoveAllFileName();
122    this->InternalFileNameList.clear();
123    if(this->LookupTable) 
124       this->LookupTable->Delete();
125 }
126
127 //-----------------------------------------------------------------------------
128 // Print
129 void vtkGdcmReader::PrintSelf(ostream &os, vtkIndent indent)
130 {
131    this->Superclass::PrintSelf(os,indent);
132    os << indent << "Filenames  : " << endl;
133    vtkIndent nextIndent = indent.GetNextIndent();
134    for (std::list<std::string>::iterator it = FileNameList.begin();
135         it != FileNameList.end();
136         ++it)
137    {
138       os << nextIndent << it->c_str() << endl ;
139    }
140 }
141
142 //-----------------------------------------------------------------------------
143 // Public
144 /*
145  * Remove all files from the list of images to read.
146  */
147 void vtkGdcmReader::RemoveAllFileName(void)
148 {
149    this->FileNameList.clear();
150    this->Modified();
151 }
152
153 /*
154  * Adds a file name to the list of images to read.
155  */
156 void vtkGdcmReader::AddFileName(const char* name)
157 {
158    // We need to bypass the const pointer [since list<>.push_bash() only
159    // takes a char* (but not a const char*)] by making a local copy:
160    this->FileNameList.push_back(name);
161    this->Modified();
162 }
163
164 /*
165  * Sets up a filename to be read.
166  */
167 void vtkGdcmReader::SetFileName(const char *name) 
168 {
169    vtkImageReader2::SetFileName(name);
170    // Since we maintain a list of filenames, when building a volume,
171    // (see vtkGdcmReader::AddFileName), we additionaly need to purge
172    // this list when we manually positionate the filename.
173    vtkDebugMacro(<< "Clearing all files given with AddFileName");
174    this->FileNameList.clear();
175    this->Modified();
176 }
177
178 //-----------------------------------------------------------------------------
179 // Protected
180 /*
181  * Configure the output e.g. WholeExtent, spacing, origin, scalar type...
182  */
183 void vtkGdcmReader::ExecuteInformation()
184 {
185 //   if(this->Execution)  // For VTK5.0
186 //      return;
187 //
188 //   this->Execution=true; // end For VTK5.0
189    this->RemoveAllInternalFile();
190    if(this->MTime>this->fileTime)
191    {
192       this->TotalNumberOfPlanes = 0;
193
194       if ( this->CoherentFileList != 0 )
195       {
196          this->UpdateFileInformation();
197       }
198       else
199       {
200          this->BuildFileListFromPattern();
201          this->LoadFileInformation();
202       }
203
204       if ( this->TotalNumberOfPlanes == 0)
205       {
206          vtkErrorMacro(<< "File set is not coherent. Exiting...");
207          return;
208       }
209
210       // if the user has not set the extent, but has set the VOI
211       // set the z axis extent to the VOI z axis
212       if (this->DataExtent[4]==0 && this->DataExtent[5] == 0 &&
213          (this->DataVOI[4] || this->DataVOI[5]))
214       {
215          this->DataExtent[4] = this->DataVOI[4];
216          this->DataExtent[5] = this->DataVOI[5];
217       }
218
219       // When the user has set the VOI, check it's coherence with the file content.
220       if (this->DataVOI[0] || this->DataVOI[1] || 
221       this->DataVOI[2] || this->DataVOI[3] ||
222       this->DataVOI[4] || this->DataVOI[5])
223       { 
224          if ((this->DataVOI[0] < 0) ||
225              (this->DataVOI[1] >= this->NumColumns) ||
226              (this->DataVOI[2] < 0) ||
227              (this->DataVOI[3] >= this->NumLines) ||
228              (this->DataVOI[4] < 0) ||
229              (this->DataVOI[5] >= this->TotalNumberOfPlanes ))
230          {
231             vtkWarningMacro(<< "The requested VOI is larger than expected extent.");
232             this->DataVOI[0] = 0;
233             this->DataVOI[1] = this->NumColumns - 1;
234             this->DataVOI[2] = 0;
235             this->DataVOI[3] = this->NumLines - 1;
236             this->DataVOI[4] = 0;
237             this->DataVOI[5] = this->TotalNumberOfPlanes - 1;
238          }
239       }
240
241       // Set the Extents.
242       this->DataExtent[0] = 0;
243       this->DataExtent[1] = this->NumColumns - 1;
244       this->DataExtent[2] = 0;
245       this->DataExtent[3] = this->NumLines - 1;
246       this->DataExtent[4] = 0;
247       this->DataExtent[5] = this->TotalNumberOfPlanes - 1;
248   
249       // We don't need to set the Endian related stuff (by using
250       // this->SetDataByteOrderToBigEndian() or SetDataByteOrderToLittleEndian()
251       // since the reading of the file is done by gdcm.
252       // But we do need to set up the data type for downstream filters:
253       if      ( ImageType == "8U" )
254       {
255          vtkDebugMacro(<< "8 bits unsigned image");
256          this->SetDataScalarTypeToUnsignedChar(); 
257       }
258       else if ( ImageType == "8S" )
259       {
260          vtkErrorMacro(<< "Cannot handle 8 bit signed files");
261          return;
262       }
263       else if ( ImageType == "16U" )
264       {
265          vtkDebugMacro(<< "16 bits unsigned image");
266          this->SetDataScalarTypeToUnsignedShort();
267       }
268       else if ( ImageType == "16S" )
269       {
270          vtkDebugMacro(<< "16 bits signed image");
271          this->SetDataScalarTypeToShort();
272       }
273       else if ( ImageType == "32U" )
274       {
275          vtkDebugMacro(<< "32 bits unsigned image");
276          vtkDebugMacro(<< "WARNING: forced to signed int !");
277          this->SetDataScalarTypeToInt();
278       }
279       else if ( ImageType == "32S" )
280       {
281          vtkDebugMacro(<< "32 bits signed image");
282          this->SetDataScalarTypeToInt();
283       }
284       else if ( ImageType == "FD" )  // This is not genuine DICOM, but so usefull
285       {
286          vtkDebugMacro(<< "64 bits Double image");
287          this->SetDataScalarTypeToDouble();
288       }
289       //Set number of scalar components:
290       this->SetNumberOfScalarComponents(this->NumComponents);
291
292       this->fileTime=this->MTime;
293    }
294
295    this->Superclass::ExecuteInformation();  
296
297    //this->GetOutput()->SetUpdateExtentToWholeExtent();// For VTK5.0
298    //this->BuildData(this->GetOutput());
299
300    //this->Execution=false;
301    //this->RemoveAllInternalFile();                   // End For VTK5.0
302 }
303  
304 /*
305  * Update => ouput->Update => UpdateData => Execute => ExecuteData 
306  * (see vtkSource.cxx for last step).
307  * This function (redefinition of vtkImageReader::ExecuteData, see 
308  * VTK/IO/vtkImageReader.cxx) reads a data from a file. The data
309  * extent/axes are assumed to be the same as the file extent/order.
310  */
311 void vtkGdcmReader::ExecuteData(vtkDataObject *output)
312 {
313    vtkImageData *data=vtkImageData::SafeDownCast(output);
314    data->SetExtent(this->DataExtent);
315
316 /*   if ( CoherentFileList != 0 )   // When a list of names is passed
317    {
318       if (this->CoherentFileList->empty())
319       {
320          vtkErrorMacro(<< "Coherent File List must have at least a valid File*.");
321          return;
322       }
323    }
324    else if (this->InternalFileNameList.empty())
325    {
326       vtkErrorMacro(<< "A least a valid FileName must be specified.");
327       return;
328    }
329 */
330   
331   // data->AllocateScalars();  // For VTK5.0
332   // if (this->UpdateExtentIsEmpty(output))
333   // {
334   //    return;
335   // }
336 //}                           // end For VTK5.0
337
338    data->AllocateScalars();  // For VTK5.0
339    
340 #if (VTK_MAJOR_VERSION >= 5) || ( VTK_MAJOR_VERSION == 4 && VTK_MINOR_VERSION > 2 )
341 //#if (VTK_MAJOR_VERSION >= 5)
342    if (this->UpdateExtentIsEmpty(output))
343    {
344       return;
345    }
346 #endif
347
348    data->GetPointData()->GetScalars()->SetName("DicomImage-Volume");
349
350    // Test if output has valid extent
351    // Prevent memory errors
352    if((this->DataExtent[1]-this->DataExtent[0]>=0) &&
353       (this->DataExtent[3]-this->DataExtent[2]>=0) &&
354       (this->DataExtent[5]-this->DataExtent[4]>=0))
355    {
356       // The memory size for a full stack of images of course depends
357       // on the number of planes and the size of each image:
358       //size_t StackNumPixels = this->NumColumns * this->NumLines
359       //                      * this->TotalNumberOfPlanes * this->NumComponents;
360       //size_t stack_size = StackNumPixels * this->PixelSize; //not used
361       // Allocate pixel data space itself.
362
363       // Variables for the UpdateProgress. We shall use 50 steps to signify
364       // the advance of the process:
365       unsigned long UpdateProgressTarget = (unsigned long) ceil (this->NumLines
366                                          * this->TotalNumberOfPlanes
367                                          / 50.0);
368       // The actual advance measure:
369       unsigned long UpdateProgressCount = 0;
370
371       // Filling the allocated memory space with each image/volume:
372
373       size_t size = this->NumColumns * this->NumLines * this->NumPlanes
374                   * data->GetScalarSize() * this->NumComponents;
375       unsigned char *Dest = (unsigned char *)data->GetScalarPointer();
376       for (std::vector<GDCM_NAME_SPACE::File* >::iterator it =  InternalFileList.begin();
377                                                it != InternalFileList.end();
378                                              ++it)
379       {
380          this->LoadImageInMemory(*it, Dest,
381                                  UpdateProgressTarget,
382                                  UpdateProgressCount); 
383          Dest += size;
384       }
385    }
386    this->RemoveAllInternalFile(); // For VTK5.0
387 }
388
389 /*
390  * vtkGdcmReader can have the file names specified through two ways:
391  * (1) by calling the vtkImageReader2::SetFileName(), SetFilePrefix() and
392  *     SetFilePattern()
393  * (2) By successive calls to vtkGdcmReader::AddFileName()
394  * When the first method was used by caller we need to update the local
395  * filename list
396  */
397 void vtkGdcmReader::BuildFileListFromPattern()
398 {
399    this->RemoveAllInternalFileName();
400
401    // Test miscellanous cases
402    if ((! this->FileNameList.empty()) && this->FileName )
403    {
404       vtkErrorMacro(<< "Both AddFileName and SetFileName schemes were used");
405       vtkErrorMacro(<< "No images loaded ! ");
406       return;
407    }
408
409    if ((! this->FileNameList.empty()) && this->FilePrefix )
410    {
411       vtkErrorMacro(<< "Both AddFileName and SetFilePrefix schemes were used");
412       vtkErrorMacro(<< "No images loaded ! ");
413       return;
414    }
415
416    if (this->FileName && this->FilePrefix)
417    {
418       vtkErrorMacro(<< "Both SetFileName and SetFilePrefix schemes were used");
419       vtkErrorMacro(<< "No images loaded ! ");
420       return;
421    }
422
423    // Create the InternalFileNameList
424    if (! this->FileNameList.empty()  )
425    {
426       vtkDebugMacro(<< "Using the AddFileName specified files");
427       this->InternalFileNameList=this->FileNameList;
428       return;
429    }
430
431    if (!this->FileName && !this->FilePrefix)
432    {
433       vtkErrorMacro(<< "FileNames are not set. Either use AddFileName() or");
434       vtkErrorMacro(<< "specify a FileName or FilePrefix.");
435       return;
436    }
437
438    if( this->FileName )
439    {
440       // Single file loading (as given with ::SetFileName()):
441       // Case of multi-frame file considered here
442       this->ComputeInternalFileName(this->DataExtent[4]);
443       vtkDebugMacro(<< "Adding file " << this->InternalFileName);
444       this->AddInternalFileName(this->InternalFileName);
445    }
446    else
447    {
448       // Multi file loading (as given with ::SetFilePattern()):
449       for (int idx = this->DataExtent[4]; idx <= this->DataExtent[5]; ++idx)
450       {
451          this->ComputeInternalFileName(idx);
452          vtkDebugMacro(<< "Adding file " << this->InternalFileName);
453          this->AddInternalFileName(this->InternalFileName);
454       }
455    }
456 }
457
458 /**
459  * Load all the files and set it in the InternalFileList
460  * For each file, the readability and the coherence of image caracteristics 
461  * are tested. If an image doesn't agree the required specifications, it
462  * isn't considered and no data will be set for the planes corresponding
463  * to this image
464  *
465  * The source of this work is the list of file name generated by the
466  * BuildFileListFromPattern method
467  */
468 void vtkGdcmReader::LoadFileInformation()
469 {
470    GDCM_NAME_SPACE::File *file;
471    bool foundReference=false;
472    std::string type;
473
474    this->OwnFile=true;
475    for (std::list<std::string>::iterator filename = InternalFileNameList.begin();
476         filename != InternalFileNameList.end();
477         ++filename)
478    {
479       // check for file readability
480       FILE *fp;
481       fp = fopen(filename->c_str(),"rb");
482       if (!fp)
483       {
484          vtkErrorMacro(<< "Unable to open file " << filename->c_str());
485          vtkErrorMacro(<< "Removing this file from read files: "
486                        << filename->c_str());
487          file = NULL;
488          InternalFileList.push_back(file);
489          continue;
490       }
491       fclose(fp);
492
493       // Read the file
494       file=GDCM_NAME_SPACE::File::New();
495       file->SetLoadMode( LoadMode );
496       file->SetFileName(filename->c_str() );
497       file->Load();
498
499       // Test the Dicom file readability
500       if(!file->IsReadable())
501       {
502          vtkErrorMacro(<< "Gdcm cannot parse file " << filename->c_str());
503          vtkErrorMacro(<< "Removing this file from read files: "
504                         << filename->c_str());
505          file->Delete();
506          file=NULL;
507          InternalFileList.push_back(file);
508          continue;
509       }
510
511       // Test the Pixel Type recognition
512       type = file->GetPixelType();
513       if (   (type !=  "8U") && (type !=  "8S")
514           && (type != "16U") && (type != "16S")
515           && (type != "32U") && (type != "32S")
516           && (type != "FD")  )                // Sure this one is NOT kosher
517       {
518          vtkErrorMacro(<< "Bad File Type for file " << filename->c_str() << "\n"
519                        << "   File type found : " << type.c_str() 
520                        << " (might be 8U, 8S, 16U, 16S, 32U, 32S, FD) \n"
521                        << "   Removing this file from read files");
522          file->Delete();
523          file=NULL;
524          InternalFileList.push_back(file);
525          continue;
526       }
527
528       // Test the image informations
529       if(!foundReference)
530       {
531          foundReference = true;
532          GetFileInformation(file);
533
534          vtkDebugMacro(<< "This file taken as coherence reference:"
535                         << filename->c_str());
536          vtkDebugMacro(<< "Image dimensions of reference file as read from Gdcm:" 
537                         << this->NumColumns << " " << this->NumLines << " " 
538                         << this->NumPlanes);
539       }
540       else if(!TestFileInformation(file))
541       {
542          file->Delete();
543          file=NULL;
544       }
545
546       InternalFileList.push_back(file);
547    }
548 }
549
550 /**
551  * Update the file informations.
552  * This works exactly like LoadFileInformation, but the source of work
553  * is the list of coherent files
554  */
555 void vtkGdcmReader::UpdateFileInformation()
556 {
557    this->InternalFileList=*(this->CoherentFileList);
558    this->OwnFile=false;
559
560    for(gdcmFileList::iterator it=InternalFileList.begin();
561                               it!=InternalFileList.end();
562                               ++it)
563    {
564       if( *it != NULL)
565       {
566          GetFileInformation(*it);
567          break;
568       }
569    }
570 }
571
572 /**
573  * Get the informations from a file.
574  * These informations are required to specify the output image
575  * caracteristics
576  */
577 void vtkGdcmReader::GetFileInformation(GDCM_NAME_SPACE::File *file)
578 {
579    // Get the image caracteristics
580    this->NumColumns = file->GetXSize();
581    this->NumLines   = file->GetYSize();
582    this->NumPlanes  = file->GetZSize();
583
584    if (CoherentFileList == 0)
585       this->TotalNumberOfPlanes = this->NumPlanes*InternalFileNameList.size();
586    else
587       this->TotalNumberOfPlanes = this->NumPlanes*CoherentFileList->size();
588
589    this->ImageType = file->GetPixelType();
590    this->PixelSize = file->GetPixelSize();
591
592    this->DataSpacing[0] = file->GetXSpacing();
593    this->DataSpacing[1] = file->GetYSpacing();
594    
595    //  Most of the file headers have NO z spacing
596    //  It must be calculated from the whole GDCM_NAME_SPACE::Serie (if any)
597    //  using Jolinda Smith's algoritm.
598    //  see GDCM_NAME_SPACE::SerieHelper::ImagePositionPatientOrdering()
599    if (CoherentFileList == 0)   
600       this->DataSpacing[2] = file->GetZSpacing();
601    else
602    {
603        // Just because OrderFileList() is a member of GDCM_NAME_SPACE::SerieHelper
604        // we need to instanciate sh.
605       GDCM_NAME_SPACE::SerieHelper *sh = GDCM_NAME_SPACE::SerieHelper::New();
606       sh->OrderFileList(CoherentFileList); // calls ImagePositionPatientOrdering()
607       this->DataSpacing[2] = sh->GetZSpacing();
608       sh->Delete();         
609    } 
610
611    // Get the image data caracteristics
612    if( file->HasLUT() && this->AllowLookupTable )
613    {
614       // I could raise an error is AllowLookupTable is on and HasLUT() off
615       this->NumComponents = file->GetNumberOfScalarComponentsRaw();
616    }
617    else
618    {
619       this->NumComponents = file->GetNumberOfScalarComponents(); //rgb or mono
620    }
621 }
622
623 /*
624  * When more than one filename is specified (i.e. we expect loading
625  * a stack or volume) we need to check that the corresponding images/volumes
626  * to be loaded are coherent i.e. to make sure:
627  *     - they all share the same X dimensions
628  *     - they all share the same Y dimensions
629  *     - they all share the same ImageType ( 8 bit signed, or unsigned...)
630  *
631  * Eventually, we emit a warning when all the files do NOT share the
632  * Z dimension, since we can still build a stack but the
633  * files are not coherent in Z, which is probably a source a trouble...
634  *   When files are not readable (either the file cannot be opened or
635  * because gdcm cannot parse it), they are flagged as "GDCM_UNREADABLE".  
636  *   This method returns the total number of planar images to be loaded
637  * (i.e. an image represents one plane, but a volume represents many planes)
638  */
639 /**
640  * Test the coherent informations of the file with the reference informations
641  * used as image caracteristics. The tested informations are :
642  * - they all share the same X dimensions
643  * - they all share the same Y dimensions
644  * - they all share the same Z dimensions
645  * - they all share the same number of components
646  * - they all share the same ImageType ( 8 bit signed, or unsigned...)
647  *
648  * \return True if the file match, False otherwise
649  */
650 bool vtkGdcmReader::TestFileInformation(GDCM_NAME_SPACE::File *file)
651 {
652    int numColumns = file->GetXSize();
653    int numLines   = file->GetYSize();
654    int numPlanes  = file->GetZSize();
655    int numComponents;
656    unsigned int pixelSize  = file->GetPixelSize();
657
658    if( file->HasLUT() && this->AllowLookupTable )
659       numComponents = file->GetNumberOfScalarComponentsRaw();
660    else
661       numComponents = file->GetNumberOfScalarComponents(); //rgb or mono
662
663    if( numColumns != this->NumColumns )
664    {
665       vtkErrorMacro(<< "File X value doesn't match with the previous ones: "
666                     << file->GetFileName().c_str()
667                     << ". Found " << numColumns << ", must be "
668                     << this->NumColumns);
669       return false;
670    }
671    if( numLines != this->NumLines )
672    {
673       vtkErrorMacro(<< "File Y value doesn't match with the previous ones: "
674                     << file->GetFileName().c_str()
675                     << ". Found " << numLines << ", must be "
676                     << this->NumLines);
677       return false;
678    }
679    if( numPlanes != this->NumPlanes )
680    {
681       vtkErrorMacro(<< "File Z value doesn't match with the previous ones: "
682                     << file->GetFileName().c_str()
683                     << ". Found " << numPlanes << ", must be "
684                     << this->NumPlanes);
685       return false;
686    }
687    if( numComponents != this->NumComponents )
688    {
689       vtkErrorMacro(<< "File Components count doesn't match with the previous ones: "
690                     << file->GetFileName().c_str()
691                     << ". Found " << numComponents << ", must be "
692                     << this->NumComponents);
693       return false;
694    }
695    if( pixelSize != this->PixelSize )
696    {
697       vtkErrorMacro(<< "File pixel size doesn't match with the previous ones: "
698                     << file->GetFileName().c_str()
699                     << ". Found " << pixelSize << ", must be "
700                     << this->PixelSize);
701       return false;
702    }
703
704    return true;
705 }
706
707 //-----------------------------------------------------------------------------
708 // Private
709 /*
710  * Remove all file names to the internal list of images to read.
711  */
712 void vtkGdcmReader::RemoveAllInternalFileName(void)
713 {
714    this->InternalFileNameList.clear();
715 }
716
717 /*
718  * Adds a file name to the internal list of images to read.
719  */
720 void vtkGdcmReader::AddInternalFileName(const char *name)
721 {
722    char *LocalName = new char[strlen(name) + 1];
723    strcpy(LocalName, name);
724    this->InternalFileNameList.push_back(LocalName);
725    delete[] LocalName;
726 }
727
728 /*
729  * Remove all file names to the internal list of images to read.
730  */
731 void vtkGdcmReader::RemoveAllInternalFile(void)
732 {
733    if(this->OwnFile)
734    {
735       for(gdcmFileList::iterator it=InternalFileList.begin();
736                                  it!=InternalFileList.end();
737                                  ++it)
738       {
739          (*it)->Delete();
740       }
741    }
742    this->InternalFileList.clear();
743 }
744
745 void vtkGdcmReader::IncrementProgress(const unsigned long updateProgressTarget,
746                                       unsigned long &updateProgressCount)
747 {
748    // Update progress related for bad files:
749    updateProgressCount += this->NumLines;
750    if (updateProgressTarget > 0)
751    {
752       if (!(updateProgressCount%updateProgressTarget))
753       {
754          this->UpdateProgress(
755              updateProgressCount/(50.0*updateProgressTarget));
756       }
757    }
758 }
759
760 /*
761  * Loads the contents of the image/volume contained by char *fileName at
762  * the dest memory address. Returns the size of the data loaded.
763  */
764 /*void vtkGdcmReader::LoadImageInMemory(
765              std::string fileName, 
766              unsigned char *dest,
767              const unsigned long updateProgressTarget,
768              unsigned long &updateProgressCount)
769 {
770    vtkDebugMacro(<< "Copying to memory image [" << fileName.c_str() << "]");
771
772    GDCM_NAME_SPACE::File *f;
773    f = new GDCM_NAME_SPACE::File();
774    f->SetLoadMode( LoadMode );
775    f->SetFileName( fileName.c_str() );
776    f->Load( );
777
778    LoadImageInMemory(f,dest,
779                      updateProgressTarget,
780                      updateProgressCount);
781    delete f;
782 }*/
783
784 /*
785  * Loads the contents of the image/volume contained by GDCM_NAME_SPACE::File* f at
786  * the Dest memory address. Returns the size of the data loaded.
787  * \ param f File to consider. NULL if the file must be skiped
788  * \remarks Assume that if (f != NULL) then its caracteristics match
789  * with the previous ones
790  */
791 void vtkGdcmReader::LoadImageInMemory(
792              GDCM_NAME_SPACE::File *f, 
793              unsigned char *dest,
794              const unsigned long updateProgressTarget,
795              unsigned long &updateProgressCount)
796 {
797    if(!f)
798       return;
799
800    GDCM_NAME_SPACE::FileHelper *fileH = GDCM_NAME_SPACE::FileHelper::New( f );
801    fileH->SetUserFunction( UserFunction );
802    
803    fileH->SetKeepOverlays ( this->KeepOverlays);
804    
805    int numColumns = f->GetXSize();
806    int numLines   = f->GetYSize();
807    int numPlanes  = f->GetZSize();
808    int numComponents;
809
810    if( f->HasLUT() && this->AllowLookupTable )
811       numComponents = f->GetNumberOfScalarComponentsRaw();
812    else
813       numComponents = f->GetNumberOfScalarComponents(); //rgb or mono
814    vtkDebugMacro(<< "numComponents:" << numComponents);
815    vtkDebugMacro(<< "Copying to memory image [" << f->GetFileName().c_str() << "]");
816    //size_t size;
817
818    // If the data structure of vtk for image/volume representation
819    // were straigthforwards the following would be enough:
820    //    GdcmFile.GetImageDataIntoVector((void*)Dest, size);
821    // But vtk chooses to invert the lines of an image, that is the last
822    // line comes first (for some axis related reasons?). Hence we need
823    // to load the image line by line, starting from the end.
824
825    int lineSize   = NumComponents * numColumns * f->GetPixelSize();
826    int planeSize  = lineSize * numLines;
827
828    unsigned char *src;
829    
830    if( fileH->GetFile()->HasLUT() && AllowLookupTable )
831    {
832       // to avoid bcc 5.5 w
833       /*size               = */ fileH->GetImageDataSize(); 
834       src                = (unsigned char*) fileH->GetImageDataRaw();
835       unsigned char *lut = (unsigned char*) fileH->GetLutRGBA();
836
837       if(!this->LookupTable)
838       {
839          this->LookupTable = vtkLookupTable::New();
840       }
841
842       this->LookupTable->SetNumberOfTableValues(256);
843       for (int tmp=0; tmp<256; tmp++)
844       {
845          this->LookupTable->SetTableValue(tmp,
846          (float)lut[4*tmp+0]/255.0,
847          (float)lut[4*tmp+1]/255.0,
848          (float)lut[4*tmp+2]/255.0,
849          1);
850       }
851       this->LookupTable->SetRange(0,255);
852       vtkDataSetAttributes *a = this->GetOutput()->GetPointData();
853       a->GetScalars()->SetLookupTable(this->LookupTable);
854       delete[] lut;
855    }
856    else
857    {
858       //size = fileH->GetImageDataSize(); 
859       // useless - just an accessor;  'size' unused
860       //if (this->GetFlipY())
861          src  = (unsigned char*)fileH->GetImageData();
862       //else
863       // very strange, but it doesn't work (I have to memcpy the pixels ?!?)
864       //   dest  = (unsigned char*)fileH->GetImageData();
865    }
866
867 if (this->GetFlipY()) {
868    unsigned char *dst = dest + planeSize - lineSize;
869    for (int plane = 0; plane < numPlanes; plane++)
870    {
871       for (int line = 0; line < numLines; line++)
872       {
873          // Copy one line at proper destination:
874          memcpy((void*)dst, (void*)src, lineSize);
875          src += lineSize;
876          dst -= lineSize;
877          // Update progress related:
878          if (!(updateProgressCount%updateProgressTarget))
879          {
880             this->UpdateProgress(
881                updateProgressCount/(50.0*updateProgressTarget));
882          }
883          updateProgressCount++;
884       }
885       dst += 2 * planeSize;
886    }
887 }
888 else // we don't flip (upside down) the image
889 {
890   memcpy((void*)dest, (void*)src,  numPlanes * numLines * lineSize);
891 }
892    fileH->Delete();
893 }
894
895 //-----------------------------------------------------------------------------