1 // $Header: /cvs/public/gdcm/vtk/vtkGdcmReader.cxx,v 1.20 2003/10/03 14:48:31 malaterre Exp $
2 // //////////////////////////////////////////////////////////////
3 // WARNING TODO CLENAME
4 // Actual limitations of this code:
6 // /////// Redundant and unnecessary header parsing
7 // In it's current state this code actually parses three times the Dicom
8 // header of a file before the corrersponding image gets loaded in the
10 // Here is the process:
11 // 1/ First loading happens in ExecuteInformation which in order to
12 // positionate the vtk extents calls CheckFileCoherence. The purpous
13 // of CheckFileCoherence is to make sure all the images in the future
14 // stack are "homogenous" (same size, same representation...). This
15 // can only be achieved by parsing all the Dicom headers...
16 // 2/ ExecuteData is then responsible for the next two loadings:
17 // 2a/ ExecuteData calls AllocateOutputData that in turn seems to
18 // (indirectely call) ExecuteInformation which ends up in a second
20 // 2b/ the core of ExecuteData then needs gdcmFile (which in turns
21 // initialiszes gdcmHeader in the constructor) in order to access
25 // maintain a list of gdcmFiles (created by say ExecuteInformation) created
26 // once and for all accross the life of vtkGdcmHeader (it would only load
27 // new gdcmFile if the user changes the list). ExecuteData would then use
28 // those gdcmFile and hence avoid calling the consctutor:
29 // - advantage: the header of the files would only be parser once.
30 // - drawback: once execute information is called (i.e. on creation of
31 // a vtkGdcmHeader) the gdcmFile sctructue is loaded in memory.
32 // The average size of a gdcmHeader being of 100Ko, is one
33 // loads 10 stacks of images with say 200 images each, you
34 // end-up with a loss of 200Mo...
36 // /////// Never unallocated memory:
37 // ExecuteData allocates space for the pixel data [which will get pointed
38 // by the vtkPointData() through the call
39 // data->GetPointData()->GetScalars()->SetVoidArray(mem, StackNumPixels, 0);]
40 // This data is never "freed" neither in the desctutor nor when the
41 // filename list is extended, ExecuteData is called a second (or third)
43 // //////////////////////////////////////////////////////////////
46 #include <vtkObjectFactory.h>
47 #include <vtkImageData.h>
48 #include <vtkPointData.h>
49 #include "vtkGdcmReader.h"
51 #include "gdcmHeaderHelper.h"
53 vtkGdcmReader::vtkGdcmReader()
58 //----------------------------------------------------------------------------
59 vtkGdcmReader::~vtkGdcmReader()
61 this->RemoveAllFileName();
62 this->InternalFileNameList.clear();
65 //----------------------------------------------------------------------------
66 // Remove all files from the list of images to read.
67 void vtkGdcmReader::RemoveAllFileName(void)
69 this->FileNameList.clear();
72 //----------------------------------------------------------------------------
73 // Adds a file name to the list of images to read.
74 void vtkGdcmReader::AddFileName(const char* name)
76 // We need to bypass the const pointer [since list<>.push_bash() only
77 // takes a char* (but not a const char*)] by making a local copy:
78 char * LocalName = new char[strlen(name) + 1];
79 strcpy(LocalName, name);
80 this->FileNameList.push_back(LocalName);
85 //----------------------------------------------------------------------------
86 // Sets up a filename to be read.
87 void vtkGdcmReader::SetFileName(const char *name) {
88 vtkImageReader2::SetFileName(name);
89 // Since we maintain a list of filenames, when building a volume,
90 // (see vtkGdcmReader::AddFileName), we additionaly need to purge
91 // this list when we manually positionate the filename.
92 this->FileNameList.clear();
96 //----------------------------------------------------------------------------
97 // Adds a file name to the internal list of images to read.
98 void vtkGdcmReader::RemoveAllInternalFileName(void)
100 this->InternalFileNameList.clear();
103 //----------------------------------------------------------------------------
104 // Adds a file name to the internal list of images to read.
105 void vtkGdcmReader::AddInternalFileName(const char* name)
107 char * LocalName = new char[strlen(name) + 1];
108 strcpy(LocalName, name);
109 this->InternalFileNameList.push_back(LocalName);
113 //----------------------------------------------------------------------------
114 // vtkGdcmReader can have the file names specified through two ways:
115 // (1) by calling the vtkImageReader2::SetFileName(), SetFilePrefix() and
117 // (2) By successive calls to vtkGdcmReader::AddFileName()
118 // When the first method was used by caller we need to update the local
120 void vtkGdcmReader::BuildFileListFromPattern()
122 if ((! this->FileNameList.empty()) && this->FileName )
124 vtkErrorMacro("Both file patterns and AddFileName schemes were used");
125 vtkErrorMacro("Only the files specified with AddFileName shall be used");
129 if (! this->FileNameList.empty() )
131 vtkDebugMacro("Using the AddFileName specified files");
132 this->InternalFileNameList=this->FileNameList;
136 if (!this->FileName && !this->FilePattern)
138 vtkErrorMacro("FileNames are not set. Either use AddFileName() or");
139 vtkErrorMacro("specify a FileName or FilePattern.");
143 this->RemoveAllInternalFileName();
144 for (int idx = this->DataExtent[4]; idx <= this->DataExtent[5]; ++idx)
146 this->ComputeInternalFileName(idx);
147 vtkDebugMacro("Adding file " << this->InternalFileName);
148 this->AddInternalFileName(this->InternalFileName);
152 //----------------------------------------------------------------------------
153 // When more than one filename is specified (i.e. we expect loading
154 // a stack or volume) we need to check that the corresponding images/volumes
155 // to be loaded are coherent i.e. to make sure:
156 // - they all share the same X dimensions
157 // - they all share the same Y dimensions
158 // - they all share the same ImageType ( 8 bit signed, or unsigned...)
160 // Eventually, we emit a warning when all the files do NOT share the
161 // Z dimension, since we can still build a stack but the
162 // files are not coherent in Z, which is probably a source a trouble...
163 // When files are not readable (either the file cannot be opened or
164 // because gdcm cannot parse it), they are flagged as "GDCM_UNREADABLE".
165 // This method returns the total number of planar images to be loaded
166 // (i.e. an image represents one plane, but a volume represents many planes)
167 int vtkGdcmReader::CheckFileCoherence()
169 int ReturnedTotalNumberOfPlanes = 0; // The returned value.
171 this->BuildFileListFromPattern();
172 if (this->InternalFileNameList.empty())
174 vtkErrorMacro("FileNames are not set.");
178 bool FoundReferenceFile = false;
181 // Loop on the filenames:
182 // - check for their existence and gdcm "parasability"
183 // - get the coherence check done:
184 for (std::list<std::string>::iterator FileName = InternalFileNameList.begin();
185 FileName != InternalFileNameList.end();
188 // The file is always added in the number of planes
189 // - If file doesn't exist, it will be replaced by a black place in the
190 // ExecuteData method
191 // - If file has more than 1 plane, other planes will be added later to
192 // to the ReturnedTotalNumberOfPlanes variable counter
193 ReturnedTotalNumberOfPlanes += 1;
195 /////// Stage 0: check for file name:
196 if(*FileName==std::string("GDCM_UNREADABLE"))
199 /////// Stage 1: check for file readability:
200 // Stage 1.1: check for file existence.
202 fp = fopen(FileName->c_str(),"rb");
205 vtkErrorMacro("Unable to open file " << FileName->c_str());
206 vtkErrorMacro("Removing this file from readed files "
207 << FileName->c_str());
208 *FileName = "GDCM_UNREADABLE";
213 // Stage 1.2: check for Gdcm parsability
214 gdcmHeaderHelper GdcmHeader(FileName->c_str());
215 if (!GdcmHeader.IsReadable())
217 vtkErrorMacro("Gdcm cannot parse file " << FileName->c_str());
218 vtkErrorMacro("Removing this file from readed files "
219 << FileName->c_str());
220 *FileName = "GDCM_UNREADABLE";
224 // Stage 1.3: further gdcm compatibility on PixelType
225 std::string type = GdcmHeader.GetPixelType();
226 if ( (type != "8U") && (type != "8S")
227 && (type != "16U") && (type != "16S")
228 && (type != "32U") && (type != "32S") )
230 vtkErrorMacro("Bad File Type for file" << FileName->c_str());
231 vtkErrorMacro("Removing this file from readed files "
232 << FileName->c_str());
233 *FileName = "GDCM_UNREADABLE";
237 /////// Stage 2: check coherence of the set of files
238 int NX = GdcmHeader.GetXSize();
239 int NY = GdcmHeader.GetYSize();
240 int NZ = GdcmHeader.GetZSize();
241 if (FoundReferenceFile)
244 // Stage 2.1: mandatory coherence stage:
245 if ( ( NX != this->NumColumns )
246 || ( NY != this->NumLines )
247 || ( type != this->ImageType ) )
249 vtkErrorMacro("This file is not coherent with previous ones"
250 << FileName->c_str());
251 vtkErrorMacro("Removing this file from readed files "
252 << FileName->c_str());
253 *FileName = "GDCM_UNREADABLE";
257 // Stage 2.2: optional coherence stage
258 if ( NZ != ReferenceNZ )
260 vtkErrorMacro("File is not coherent in Z with previous ones"
261 << FileName->c_str());
265 vtkDebugMacro("File is coherent with previous ones"
266 << FileName->c_str());
269 // Stage 2.3: when the file contains a volume (as opposed to an image),
270 // notify the caller.
273 vtkErrorMacro("This file contains multiple planes (images)"
274 << FileName->c_str());
277 // Eventually, this file can be added on the stack. Update the
278 // full size of the stack
279 vtkDebugMacro("Number of planes added to the stack: " << NZ);
280 ReturnedTotalNumberOfPlanes += NZ - 1; // First plane already added
284 // We didn't have a workable reference file yet. Set this one
286 FoundReferenceFile = true;
287 vtkDebugMacro("This file taken as coherence reference:"
288 << FileName->c_str());
289 vtkDebugMacro("Image dimension of reference file as read from Gdcm:" <<
290 NX << " " << NY << " " << NZ);
291 vtkDebugMacro("Number of planes added to the stack: " << NZ);
292 // Set aside the size of the image
293 this->NumColumns = NX;
296 ReturnedTotalNumberOfPlanes += NZ - 1; // First plane already added
297 this->ImageType = type;
298 this->PixelSize = GdcmHeader.GetPixelSize();
299 this->NumComponents = GdcmHeader.GetNumberOfScalarComponents(); //rgb or mono
302 this->DataSpacing[0] = GdcmHeader.GetXSpacing();
303 this->DataSpacing[1] = GdcmHeader.GetYSpacing();
304 this->DataSpacing[2] = GdcmHeader.GetZSpacing();
307 this->DataOrigin[0] = GdcmHeader.GetXOrigin();
308 this->DataOrigin[1] = GdcmHeader.GetYOrigin();
309 this->DataOrigin[2] = GdcmHeader.GetZOrigin();
312 } // End of loop on FileName
314 ///////// The files we CANNOT load are flaged. On debugging purposes
315 // count the loadable number of files and display thir number:
316 int NumberCoherentFiles = 0;
317 for (std::list<std::string>::iterator Filename = InternalFileNameList.begin();
318 Filename != InternalFileNameList.end();
321 if (*Filename != "GDCM_UNREADABLE")
322 NumberCoherentFiles++;
324 vtkDebugMacro("Number of coherent files: " << NumberCoherentFiles);
326 if (ReturnedTotalNumberOfPlanes == 0)
328 vtkErrorMacro("No loadable file.");
331 vtkDebugMacro("Total number of planes on the stack: "
332 << ReturnedTotalNumberOfPlanes);
334 return ReturnedTotalNumberOfPlanes;
337 //----------------------------------------------------------------------------
338 // Configure the output e.g. WholeExtent, spacing, origin, scalar type...
339 void vtkGdcmReader::ExecuteInformation()
341 this->TotalNumberOfPlanes = this->CheckFileCoherence();
342 if ( this->TotalNumberOfPlanes == 0)
344 vtkErrorMacro("File set is not coherent. Exiting...");
348 // if the user has not set the extent, but has set the VOI
349 // set the zaxis extent to the VOI z axis
350 if (this->DataExtent[4]==0 && this->DataExtent[5] == 0 &&
351 (this->DataVOI[4] || this->DataVOI[5]))
353 this->DataExtent[4] = this->DataVOI[4];
354 this->DataExtent[5] = this->DataVOI[5];
357 // When the user has set the VOI, check it's coherence with the file content.
358 if (this->DataVOI[0] || this->DataVOI[1] ||
359 this->DataVOI[2] || this->DataVOI[3] ||
360 this->DataVOI[4] || this->DataVOI[5])
362 if ((this->DataVOI[0] < 0) ||
363 (this->DataVOI[1] >= this->NumColumns) ||
364 (this->DataVOI[2] < 0) ||
365 (this->DataVOI[3] >= this->NumLines) ||
366 (this->DataVOI[4] < 0) ||
367 (this->DataVOI[5] >= this->TotalNumberOfPlanes ))
369 vtkWarningMacro("The requested VOI is larger than expected extent.");
370 this->DataVOI[0] = 0;
371 this->DataVOI[1] = this->NumColumns - 1;
372 this->DataVOI[2] = 0;
373 this->DataVOI[3] = this->NumLines - 1;
374 this->DataVOI[4] = 0;
375 this->DataVOI[5] = this->TotalNumberOfPlanes - 1;
379 // Positionate the Extent.
380 this->DataExtent[0] = 0;
381 this->DataExtent[1] = this->NumColumns - 1;
382 this->DataExtent[2] = 0;
383 this->DataExtent[3] = this->NumLines - 1;
384 if(this->InternalFileNameList.size() > 1)
386 this->DataExtent[4] = 0;
387 this->DataExtent[5] = this->TotalNumberOfPlanes - 1;
390 // We don't need to positionate the Endian related stuff (by using
391 // this->SetDataByteOrderToBigEndian() or SetDataByteOrderToLittleEndian()
392 // since the reading of the file is done by gdcm.
393 // But we do need to set up the data type for downstream filters:
394 if ( ImageType == "8U" )
396 vtkDebugMacro("8 bits unsigned image");
397 this->SetDataScalarTypeToUnsignedChar();
399 else if ( ImageType == "8S" )
401 vtkErrorMacro("Cannot handle 8 bit signed files");
404 else if ( ImageType == "16U" )
406 vtkDebugMacro("16 bits unsigned image");
407 this->SetDataScalarTypeToUnsignedShort();
409 else if ( ImageType == "16S" )
411 vtkDebugMacro("16 bits signed image");
412 this->SetDataScalarTypeToShort();
413 //vtkErrorMacro("Cannot handle 16 bit signed files");
415 else if ( ImageType == "32U" )
417 vtkDebugMacro("32 bits unsigned image");
418 vtkDebugMacro("WARNING: forced to signed int !");
419 this->SetDataScalarTypeToInt();
421 else if ( ImageType == "32S" )
423 vtkDebugMacro("32 bits signed image");
424 this->SetDataScalarTypeToInt();
427 //Set number of scalar components:
428 this->SetNumberOfScalarComponents(this->NumComponents);
430 vtkImageReader::ExecuteInformation();
433 //----------------------------------------------------------------------------
434 // Loads the contents of the image/volume contained by Filename at
435 // the Dest memory address. Returns the size of the data loaded.
436 size_t vtkGdcmReader::LoadImageInMemory(
437 std::string FileName,
438 unsigned char * Dest,
439 const unsigned long UpdateProgressTarget,
440 unsigned long & UpdateProgressCount)
442 vtkDebugMacro("Copying to memory image" << FileName.c_str());
443 gdcmFile GdcmFile(FileName.c_str());
444 size_t size = GdcmFile.GetImageDataSize();
446 // If the data structure of vtk for image/volume representation
447 // were straigthforwards the following would suffice:
448 // GdcmFile.GetImageDataIntoVector((void*)Dest, size);
449 // But vtk chose to invert the lines of an image, that is the last
450 // line comes first (for some axis related reasons?). Hence we need
451 // to load the image line by line, starting from the end:
452 int NumColumns = GdcmFile.GetXSize();
453 int NumLines = GdcmFile.GetYSize();
454 int NumPlanes = GdcmFile.GetZSize();
455 int LineSize = NumComponents * NumColumns * GdcmFile.GetPixelSize();
456 unsigned char * Source = (unsigned char*)GdcmFile.GetImageData();
457 unsigned char * pSource = Source; //pointer for later deletion
458 unsigned char * Destination = Dest + size - LineSize;
460 for (int plane = 0; plane < NumPlanes; plane++)
462 for (int line = 0; line < NumLines; line++)
464 // Copy one line at proper destination:
465 memcpy((void*)Destination, (void*)Source, LineSize);
467 Destination -= LineSize;
468 // Update progress related:
469 if (!(UpdateProgressCount%UpdateProgressTarget))
471 this->UpdateProgress(UpdateProgressCount/(50.0*UpdateProgressTarget));
473 UpdateProgressCount++;
476 //GetImageData allocate a (void*)malloc, remove it:
482 //----------------------------------------------------------------------------
483 // Update => ouput->Update => UpdateData => Execute => ExecuteData
484 // (see vtkSource.cxx for last step).
485 // This function (redefinition of vtkImageReader::ExecuteData, see
486 // VTK/IO/vtkImageReader.cxx) reads a data from a file. The datas
487 // extent/axes are assumed to be the same as the file extent/order.
488 void vtkGdcmReader::ExecuteData(vtkDataObject *output)
490 if (this->InternalFileNameList.empty())
492 vtkErrorMacro("A least a valid FileName must be specified.");
496 // FIXME : extraneous parsing of header is made when allocating OuputData
497 vtkImageData *data = this->AllocateOutputData(output);
498 data->SetExtent(this->DataExtent);
499 data->GetPointData()->GetScalars()->SetName("DicomImage-Volume");
501 // Test if output has valid extent
502 // Prevent memory errors
503 if((this->DataExtent[1]-this->DataExtent[0]>=0) &&
504 (this->DataExtent[3]-this->DataExtent[2]>=0) &&
505 (this->DataExtent[5]-this->DataExtent[4]>=0))
507 // The memory size for a full stack of images of course depends
508 // on the number of planes and the size of each image:
509 size_t StackNumPixels = this->NumColumns * this->NumLines
510 * this->TotalNumberOfPlanes * this->NumComponents;
511 size_t stack_size = StackNumPixels * this->PixelSize;
512 // Allocate pixel data space itself.
513 unsigned char *mem = new unsigned char [stack_size];
515 // Variables for the UpdateProgress. We shall use 50 steps to signify
516 // the advance of the process:
517 unsigned long UpdateProgressTarget = (unsigned long) ceil (this->NumLines
518 * this->TotalNumberOfPlanes
520 // The actual advance measure:
521 unsigned long UpdateProgressCount = 0;
523 // Feeling the allocated memory space with each image/volume:
524 unsigned char * Dest = mem;
525 for (std::list<std::string>::iterator FileName = InternalFileNameList.begin();
526 FileName != InternalFileNameList.end();
529 // Images that were tagged as unreadable in CheckFileCoherence()
530 // are substituted with a black image to let the caller visually
531 // notice something wrong is going on:
532 if (*FileName != "GDCM_UNREADABLE")
534 // Update progress related for good files is made in LoadImageInMemory
535 Dest += this->LoadImageInMemory(*FileName, Dest,
536 UpdateProgressTarget,
537 UpdateProgressCount);
539 // We insert a black image in the stack for the user to be aware that
540 // this image/volume couldn't be loaded. We simply skip one image
542 Dest += this->NumColumns * this->NumLines * this->PixelSize;
544 // Update progress related for bad files:
545 UpdateProgressCount += this->NumLines;
546 if (UpdateProgressTarget > 0)
548 if (!(UpdateProgressCount%UpdateProgressTarget))
550 this->UpdateProgress(UpdateProgressCount/(50.0*UpdateProgressTarget));
553 } // Else, file not loadable
556 // The "size" of the vtkScalars data is expressed in number of points,
557 // and is not the memory size representing those points:
558 data->GetPointData()->GetScalars()->SetVoidArray(mem, StackNumPixels, 0);
563 //----------------------------------------------------------------------------
564 void vtkGdcmReader::PrintSelf(ostream& os, vtkIndent indent)
566 vtkImageReader::PrintSelf(os,indent);
567 os << indent << "Filenames : " << endl;
568 vtkIndent nextIndent = indent.GetNextIndent();
569 for (std::list<std::string>::iterator FileName = FileNameList.begin();
570 FileName != FileNameList.end();
573 os << nextIndent << FileName->c_str() << endl ;