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