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