]> Creatis software - gdcm.git/blob - vtk/vtkGdcmReader.cxx
* src/gdcmHeader.h : added method to get the file name
[gdcm.git] / vtk / vtkGdcmReader.cxx
1 // $Header: /cvs/public/gdcm/vtk/vtkGdcmReader.cxx,v 1.14 2003/07/04 17:12:43 regrain Exp $
2 #include <stdio.h>
3 #include <vtkObjectFactory.h>
4 #include <vtkImageData.h>
5 #include <vtkPointData.h>
6 #include "vtkGdcmReader.h"
7 #include "gdcm.h"
8
9 vtkGdcmReader::vtkGdcmReader()
10 {
11   // Constructor
12 }
13
14 //----------------------------------------------------------------------------
15 vtkGdcmReader::~vtkGdcmReader()
16
17   // FIXME free memory
18   this->FileNameList.clear();
19 }
20
21 //----------------------------------------------------------------------------
22 // Remove all files from the list of images to read.
23 void vtkGdcmReader::RemoveAllFileName(void)
24 {
25   this->FileNameList.clear();
26 }
27
28 //----------------------------------------------------------------------------
29 // Adds a file name to the list of images to read.
30 void vtkGdcmReader::AddFileName(const char* name)
31 {
32   // We need to bypass the const pointer [since list<>.push_bash() only
33   // takes a char* (but not a const char*)] by making a local copy:
34   char * LocalName = new char[strlen(name) + 1];
35   strcpy(LocalName, name);
36   this->FileNameList.push_back(LocalName);
37   this->Modified();
38   delete[] LocalName;
39 }
40
41 //----------------------------------------------------------------------------
42 // Sets up a filename to be read.
43 void vtkGdcmReader::SetFileName(const char *name) {
44   vtkImageReader2::SetFileName(name);
45   // Since we maintain a list of filenames, when building a volume,
46   // (see vtkGdcmReader::AddFileName), we additionaly need to purge
47   // this list when we manually positionate the filename:
48   this->FileNameList.clear();
49   this->Modified();
50 }
51
52 //----------------------------------------------------------------------------
53 // vtkGdcmReader can have the file names specified through two ways:
54 // (1) by calling the vtkImageReader2::SetFileName(), SetFilePrefix() and
55 //     SetFilePattern()
56 // (2) By successive calls to vtkGdcmReader::AddFileName()
57 // When the first method was used by caller we need to update the local
58 // filename list
59 void vtkGdcmReader::BuildFileListFromPattern()
60 {
61    if ((! this->FileNameList.empty()) && this->FileName )
62      {
63      vtkErrorMacro("Both file patterns and AddFileName schemes were used");
64      vtkErrorMacro("Only the files specified with AddFileName shall be used");
65      return;
66      }
67
68    if (! this->FileNameList.empty()  )
69      {
70      vtkDebugMacro("Using the AddFileName specified files");
71      return;
72      }
73
74    if (!this->FileName && !this->FilePattern)
75      {
76      vtkErrorMacro("FileNames are not set. Either use AddFileName() or");
77      vtkErrorMacro("specify a FileName or FilePattern.");
78      return;
79      }
80
81    for (int idx = this->DataExtent[4]; idx <= this->DataExtent[5]; ++idx)
82      {
83      this->ComputeInternalFileName(idx);
84      vtkDebugMacro("Adding file " << this->InternalFileName);
85      this->AddFileName(this->InternalFileName);
86      }
87 }
88
89 //----------------------------------------------------------------------------
90 // When more than one filename is specified (i.e. we expect loading
91 // a stack or volume) we need to check that the corresponding images/volumes
92 // to be loaded are coherent i.e. to make sure:
93 //     - they all share the same X dimensions
94 //     - they all share the same Y dimensions
95 //     - they all share the same ImageType ( 8 bit signed, or unsigned...)
96 //
97 // Eventually, we emit a warning when all the files do NOT share the
98 // Z dimension, since we can still build a stack but the
99 // files are not coherent in Z, which is probably a source a trouble...
100 //   When files are not readable (either the file cannot be opened or
101 // because gdcm cannot parse it), they are flagged as "GDCM_UNREADABLE".  
102 //   This method returns the total number of planar images to be loaded
103 // (i.e. an image represents one plane, but a volume represents many planes)
104 int vtkGdcmReader::CheckFileCoherence()
105 {
106         int ReturnedTotalNumberOfPlanes = 0;   // The returned value.
107
108    this->BuildFileListFromPattern();
109    if (this->FileNameList.empty())
110      {
111      vtkErrorMacro("FileNames are not set.");
112      return 0;
113      }
114
115    bool FoundReferenceFile = false;
116    int  ReferenceNZ = 0;
117
118    // Loop on the filenames:
119    // - check for their existence and gdcm "parasability"
120    // - get the coherence check done:
121    for (std::list<std::string>::iterator FileName  = FileNameList.begin();
122                                         FileName != FileNameList.end();
123                                       ++FileName)
124      {
125      // The file is always added in the number of planes
126      //  - If file doesn't exist, it will be replaced by a black place in the 
127      //    ExecuteData method
128      //  - If file has more than 1 plane, other planes will be added later to
129      //    to the ReturnedTotalNumberOfPlanes variable counter
130      ReturnedTotalNumberOfPlanes += 1;
131
132      /////// Stage 0: check for file name:
133           if(*FileName==std::string("GDCM_UNREADABLE"))
134                   continue;
135
136      /////// Stage 1: check for file readability:
137      // Stage 1.1: check for file existence.
138      FILE *fp;
139      fp = fopen(FileName->c_str(),"rb");
140      if (!fp)
141        {
142        vtkErrorMacro("Unable to open file " << FileName->c_str());
143        vtkErrorMacro("Removing this file from readed files "
144                      << FileName->c_str());
145        *FileName = "GDCM_UNREADABLE";
146        continue;
147        }
148      fclose(fp);
149    
150      // Stage 1.2: check for Gdcm parsability
151      gdcmHeader GdcmHeader(FileName->c_str());
152      if (!GdcmHeader.IsReadable())
153        {
154        vtkErrorMacro("Gdcm cannot parse file " << FileName->c_str());
155        vtkErrorMacro("Removing this file from readed files "
156                      << FileName->c_str());
157        *FileName = "GDCM_UNREADABLE";
158        continue;
159        }
160
161      // Stage 1.3: further gdcm compatibility on PixelType
162      std::string type = GdcmHeader.GetPixelType();
163      if (   (type !=  "8U") && (type !=  "8S")
164          && (type != "16U") && (type != "16S")
165          && (type != "32U") && (type != "32S") )
166        {
167        vtkErrorMacro("Bad File Type for file" << FileName->c_str());
168        vtkErrorMacro("Removing this file from readed files "
169                      << FileName->c_str());
170        *FileName = "GDCM_UNREADABLE";
171        continue;
172        }
173
174      /////// Stage 2: check coherence of the set of files
175      int NX = GdcmHeader.GetXSize();
176      int NY = GdcmHeader.GetYSize();
177      int NZ = GdcmHeader.GetZSize();
178      if (FoundReferenceFile) 
179        {
180         
181        // Stage 2.1: mandatory coherence stage:
182        if (   ( NX   != this->NumColumns )
183            || ( NY   != this->NumLines )
184            || ( type != this->ImageType ) ) 
185          {
186          vtkErrorMacro("This file is not coherent with previous ones"
187                        << FileName->c_str());
188          vtkErrorMacro("Removing this file from readed files "
189                        << FileName->c_str());
190          *FileName = "GDCM_UNREADABLE";
191          continue;
192          }
193
194        // Stage 2.2: optional coherence stage
195        if ( NZ != ReferenceNZ )
196          {
197          vtkErrorMacro("File is not coherent in Z with previous ones"
198                        << FileName->c_str());
199          }
200        else
201          {
202          vtkDebugMacro("File is coherent with previous ones"
203                        << FileName->c_str());
204          }
205
206        // Stage 2.3: when the file contains a volume (as opposed to an image),
207        // notify the caller.
208        if (NZ > 1)
209          {
210          vtkErrorMacro("This file contains multiple planes (images)"
211                        << FileName->c_str());
212          }
213
214        // Eventually, this file can be added on the stack. Update the
215        // full size of the stack
216        vtkDebugMacro("Number of planes added to the stack: " << NZ);
217        ReturnedTotalNumberOfPlanes += NZ - 1; // First plane already added
218        continue;
219
220        } else {
221        // We didn't have a workable reference file yet. Set this one
222        // as the reference.
223        FoundReferenceFile = true;
224        vtkDebugMacro("This file taken as coherence reference:"
225                      << FileName->c_str());
226        vtkDebugMacro("Image dimension of reference file as read from Gdcm:" <<
227                      NX << " " << NY << " " << NZ);
228        vtkDebugMacro("Number of planes added to the stack: " << NZ);
229        // Set aside the size of the image
230        this->NumColumns = NX;
231        this->NumLines   = NY;
232        ReferenceNZ      = NZ;
233        ReturnedTotalNumberOfPlanes += NZ - 1; // First plane already added
234        this->ImageType = type;
235        this->PixelSize = GdcmHeader.GetPixelSize();
236        }
237      } // End of loop on FileName
238
239    ///////// The files we CANNOT load are flaged. On debugging purposes
240    // count the loadable number of files and display thir number:
241    int NumberCoherentFiles = 0;
242    for (std::list<std::string>::iterator Filename  = FileNameList.begin();
243                                         Filename != FileNameList.end();
244                                       ++Filename)
245      {
246      if (*Filename != "GDCM_UNREADABLE")
247         NumberCoherentFiles++;    
248      }
249    vtkDebugMacro("Number of coherent files: " << NumberCoherentFiles);
250
251    if (ReturnedTotalNumberOfPlanes == 0)
252      {
253      vtkErrorMacro("No loadable file.");
254      }
255
256    vtkDebugMacro("Total number of planes on the stack: "
257                  << ReturnedTotalNumberOfPlanes);
258    
259         return ReturnedTotalNumberOfPlanes;
260 }
261
262 //----------------------------------------------------------------------------
263 // Configure the output e.g. WholeExtent, spacing, origin, scalar type...
264 void vtkGdcmReader::ExecuteInformation()
265 {
266         //FIXME free any old memory
267   this->TotalNumberOfPlanes = this->CheckFileCoherence();
268   if ( this->TotalNumberOfPlanes == 0)
269     {
270        vtkErrorMacro("File set is not coherent. Exiting...");
271        return;
272     }
273       
274   // if the user has not set the extent, but has set the VOI
275   // set the zaxis extent to the VOI z axis
276   if (this->DataExtent[4]==0 && this->DataExtent[5] == 0 &&
277      (this->DataVOI[4] || this->DataVOI[5]))
278     {
279     this->DataExtent[4] = this->DataVOI[4];
280     this->DataExtent[5] = this->DataVOI[5];
281     }
282
283   // When the user has set the VOI, check it's coherence with the file content.
284   if (this->DataVOI[0] || this->DataVOI[1] || 
285       this->DataVOI[2] || this->DataVOI[3] ||
286       this->DataVOI[4] || this->DataVOI[5])
287     { 
288     if ((this->DataVOI[0] < 0) ||
289         (this->DataVOI[1] >= this->NumColumns) ||
290         (this->DataVOI[2] < 0) ||
291         (this->DataVOI[3] >= this->NumLines) ||
292         (this->DataVOI[4] < 0) ||
293         (this->DataVOI[5] >= this->TotalNumberOfPlanes ))
294       {
295       vtkWarningMacro("The requested VOI is larger than expected extent.");
296       this->DataVOI[0] = 0;
297       this->DataVOI[1] = this->NumColumns - 1;
298       this->DataVOI[2] = 0;
299       this->DataVOI[3] = this->NumLines - 1;
300       this->DataVOI[4] = 0;
301       this->DataVOI[5] = this->TotalNumberOfPlanes - 1;
302       }
303     }
304
305   // Positionate the Extent.
306   this->DataExtent[0] = 0;
307   this->DataExtent[1] = this->NumColumns - 1;
308   this->DataExtent[2] = 0;
309   this->DataExtent[3] = this->NumLines - 1;
310   if(this->FileNameList.size() > 1)
311     {
312     this->DataExtent[4] = 0;
313     this->DataExtent[5] = this->TotalNumberOfPlanes - 1;
314     }
315   
316   // We don't need to positionate the Endian related stuff (by using
317   // this->SetDataByteOrderToBigEndian() or SetDataByteOrderToLittleEndian()
318   // since the reading of the file is done by gdcm.
319   // But we do need to set up the data type for downstream filters:
320   if      ( ImageType == "8U" )
321     {
322     vtkDebugMacro("8 bits unsigned image");
323     this->SetDataScalarTypeToUnsignedChar(); 
324     }
325   else if ( ImageType == "8S" )
326     {
327     vtkErrorMacro("Cannot handle 8 bit signed files");
328     return;
329     }
330   else if ( ImageType == "16U" )
331     {
332     vtkDebugMacro("16 bits unsigned image");
333     this->SetDataScalarTypeToUnsignedShort();
334     }
335   else if ( ImageType == "16S" )
336     {
337     vtkDebugMacro("16 bits signed image");
338     this->SetDataScalarTypeToShort();
339     //vtkErrorMacro("Cannot handle 16 bit signed files");
340     }
341   else if ( ImageType == "32U" )
342     {
343     vtkDebugMacro("32 bits unsigned image");
344     vtkDebugMacro("WARNING: forced to signed int !");
345     this->SetDataScalarTypeToInt();
346     }
347   else if ( ImageType == "32S" )
348     {
349     vtkDebugMacro("32 bits signed image");
350     this->SetDataScalarTypeToInt();
351     }
352
353   vtkImageReader::ExecuteInformation();
354 }
355
356 //----------------------------------------------------------------------------
357 // Loads the contents of the image/volume contained by Filename at
358 // the Dest memory address. Returns the size of the data loaded.
359 size_t vtkGdcmReader::LoadImageInMemory(
360              std::string FileName, 
361              unsigned char * Dest,
362              const unsigned long UpdateProgressTarget,
363              unsigned long & UpdateProgressCount)
364 {
365   vtkDebugMacro("Copying to memmory image" << FileName.c_str());
366   gdcmFile GdcmFile(FileName.c_str());
367   size_t size = GdcmFile.GetImageDataSize();
368
369   // If the data structure of vtk for image/volume representation
370   // were straigthforwards the following would suffice:
371   //    GdcmFile.GetImageDataIntoVector((void*)Dest, size);
372   // But vtk chose to invert the lines of an image, that is the last
373   // line comes first (for some axis related reasons?). Hence we need
374   // to load the image line by line, starting from the end:
375   int NumColumns = GdcmFile.GetXSize();
376   int NumLines   = GdcmFile.GetYSize();
377   int NumPlanes  = GdcmFile.GetZSize();
378   int LineSize   = NumColumns * GdcmFile.GetPixelSize();
379   unsigned char * Source      = (unsigned char*)GdcmFile.GetImageData();
380   unsigned char * Destination = Dest + size - LineSize;
381
382   for (int plane = 0; plane < NumPlanes; plane++)
383     {
384     for (int line = 0; line < NumLines; line++)
385       {
386       // Copy one line at proper destination:
387       memcpy((void*)Destination, (void*)Source, LineSize);
388       Source      += LineSize;
389       Destination -= LineSize;
390       // Update progress related:
391       if (!(UpdateProgressCount%UpdateProgressTarget))
392         {
393         this->UpdateProgress(UpdateProgressCount/(50.0*UpdateProgressTarget));
394         }
395       UpdateProgressCount++;
396       }
397     }
398   return size;
399 }
400
401 //----------------------------------------------------------------------------
402 // Update => ouput->Update => UpdateData => Execute => ExecuteData 
403 // (see vtkSource.cxx for last step).
404 // This function (redefinition of vtkImageReader::ExecuteData, see 
405 // VTK/IO/vtkImageReader.cxx) reads a data from a file. The datas
406 // extent/axes are assumed to be the
407 // same as the file extent/order.
408 void vtkGdcmReader::ExecuteData(vtkDataObject *output)
409 {
410   if (this->FileNameList.empty())
411     {
412     vtkErrorMacro("A least a valid FileName must be specified.");
413     return;
414     }
415
416   // FIXME : the bad parse of header is made when allocating OuputData
417   vtkImageData *data = this->AllocateOutputData(output);
418   data->SetExtent(this->DataExtent);
419   data->GetPointData()->GetScalars()->SetName("DicomImage-Volume");
420
421   // The memory size for a full stack of images of course depends
422   // on the number of planes and the size of each image:
423   size_t StackNumPixels = this->NumColumns * this->NumLines
424                         * this->TotalNumberOfPlanes;
425   size_t stack_size = StackNumPixels * this->PixelSize;
426   // Allocate pixel data space itself.
427   unsigned char *mem = new unsigned char [stack_size];
428
429   // Variables for the UpdateProgress. We shall use 50 steps to signify
430   // the advance of the process:
431   unsigned long UpdateProgressTarget = (unsigned long) ceil (this->NumLines
432                                      * this->TotalNumberOfPlanes
433                                      / 50.0);
434   // The actual advance measure:
435   unsigned long UpdateProgressCount = 0;
436
437   // Feeling the allocated memory space with each image/volume:
438   unsigned char * Dest = mem;
439   for (std::list<std::string>::iterator FileName  = FileNameList.begin();
440                                         FileName != FileNameList.end();
441                                       ++FileName)
442     { 
443     // Images that were tagged as unreadable in CheckFileCoherence()
444     // are substituted with a black image to let the caller visually
445     // notice something wrong is going on:
446     if (*FileName != "GDCM_UNREADABLE")
447       {
448       Dest += this->LoadImageInMemory(*FileName, Dest,
449                                       UpdateProgressTarget,
450                                       UpdateProgressCount);
451       } else {
452       // We insert a black image in the stack for the user to be aware that
453       // this image/volume couldn't be loaded. We simply skip one image
454       // size:
455       Dest += this->NumColumns * this->NumLines * this->PixelSize;
456       } // Else, file not loadable
457
458     // Update progress related:
459     UpdateProgressCount += this->NumLines;
460     if (!(UpdateProgressCount%UpdateProgressTarget))
461                 {
462       this->UpdateProgress(UpdateProgressCount/(50.0*UpdateProgressTarget));
463                 }
464     } // Loop on files
465
466   // The "size" of the vtkScalars data is expressed in number of points,
467   // and is not the memory size representing those points:
468   data->GetPointData()->GetScalars()->SetVoidArray(mem, StackNumPixels, 0);
469   this->Modified();
470 }
471
472 //----------------------------------------------------------------------------
473 void vtkGdcmReader::PrintSelf(ostream& os, vtkIndent indent)
474 {
475   vtkImageReader::PrintSelf(os,indent);
476   os << indent << "Filenames  : " << endl;
477   vtkIndent nextIndent = indent.GetNextIndent();
478   for (std::list<std::string>::iterator FileName  = FileNameList.begin();
479                                         FileName != FileNameList.end();
480                                       ++FileName)
481     {
482     os << nextIndent << FileName->c_str() << endl ;
483     }
484 }