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