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