1 /*=========================================================================
4 Module: $RCSfile: vtkGdcmReader.cxx,v $
6 Date: $Date: 2005/04/22 12:07:39 $
7 Version: $Revision: 1.68 $
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.
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.
17 =========================================================================*/
19 //-----------------------------------------------------------------------------
20 // //////////////////////////////////////////////////////////////
21 // WARNING TODO CLEANME
22 // Actual limitations of this code:
24 // /////// Redundant and unnecessary header parsing
25 // In it's current state this code actually parses three times the Dicom
26 // header of a file before the corresponding image gets loaded in the
28 // Here is the process:
29 // 1/ First loading happens in ExecuteInformation which in order to
30 // positionate the vtk extents calls CheckFileCoherence. The purpose
31 // of CheckFileCoherence is to make sure all the images in the future
32 // stack are "homogenous" (same size, same representation...). This
33 // can only be achieved by parsing all the Dicom headers...
34 // 2/ ExecuteData is then responsible for the next two loadings:
35 // 2a/ ExecuteData calls AllocateOutputData that in turn seems to
36 // (indirectely call) ExecuteInformation which ends up in a second
38 // This is fixed by adding a test at the beginning of ExecuteInformation
39 // on the modification of the object instance. If a modification have been
40 // made (method Modified() ), the MTime value is increased. The fileTime
41 // is compared to this new value to find a modification in the class
43 // 2b/ the core of ExecuteData then needs gdcmFile (which in turns
44 // initialises gdcmFile in the constructor) in order to access
48 // maintain a list of gdcmFiles (created by say ExecuteInformation) created
49 // once and for all accross the life of vtkGdcmFile (it would only load
50 // new gdcmFile if the user changes the list). ExecuteData would then use
51 // those gdcmFile and hence avoid calling the construtor:
52 // - advantage: the header of the files would only be parser once.
53 // - drawback: once execute information is called (i.e. on creation of
54 // a vtkGdcmFile) the gdcmFile structure is loaded in memory.
55 // The average size of a gdcmFile being of 100Ko, is one
56 // loads 10 stacks of images with say 200 images each, you
57 // end-up with a loss of 200Mo...
59 // /////// Never unallocated memory:
60 // ExecuteData allocates space for the pixel data [which will get pointed
61 // by the vtkPointData() through the call
62 // data->GetPointData()->GetScalars()->SetVoidArray(mem, StackNumPixels, 0);]
63 // This data is never "freed" neither in the destructor nor when the
64 // filename list is extended, ExecuteData is called a second (or third)
66 // //////////////////////////////////////////////////////////////
68 #include "gdcmFileHelper.h"
70 #include "vtkGdcmReader.h"
73 #include <vtkObjectFactory.h>
74 #include <vtkImageData.h>
75 #include <vtkPointData.h>
76 #include <vtkLookupTable.h>
78 vtkCxxRevisionMacro(vtkGdcmReader, "$Revision: 1.68 $");
79 vtkStandardNewMacro(vtkGdcmReader);
81 //-----------------------------------------------------------------------------
82 // Constructor / Destructor
83 vtkGdcmReader::vtkGdcmReader()
85 this->LookupTable = NULL;
86 this->AllowLookupTable = 0;
89 vtkGdcmReader::~vtkGdcmReader()
91 this->RemoveAllFileName();
92 this->InternalFileNameList.clear();
94 this->LookupTable->Delete();
97 //-----------------------------------------------------------------------------
99 void vtkGdcmReader::PrintSelf(ostream& os, vtkIndent indent)
101 this->Superclass::PrintSelf(os,indent);
102 os << indent << "Filenames : " << endl;
103 vtkIndent nextIndent = indent.GetNextIndent();
104 for (std::list<std::string>::iterator it = FileNameList.begin();
105 it != FileNameList.end();
108 os << nextIndent << it->c_str() << endl ;
112 //-----------------------------------------------------------------------------
115 * Remove all files from the list of images to read.
117 void vtkGdcmReader::RemoveAllFileName(void)
119 this->FileNameList.clear();
124 * Adds a file name to the list of images to read.
126 void vtkGdcmReader::AddFileName(const char* name)
128 // We need to bypass the const pointer [since list<>.push_bash() only
129 // takes a char* (but not a const char*)] by making a local copy:
130 char * LocalName = new char[strlen(name) + 1];
131 strcpy(LocalName, name);
132 this->FileNameList.push_back(LocalName);
138 * Sets up a filename to be read.
140 void vtkGdcmReader::SetFileName(const char *name)
142 vtkImageReader2::SetFileName(name);
143 // Since we maintain a list of filenames, when building a volume,
144 // (see vtkGdcmReader::AddFileName), we additionaly need to purge
145 // this list when we manually positionate the filename.
146 vtkDebugMacro(<< "Clearing all files given with AddFileName");
147 this->FileNameList.clear();
151 //-----------------------------------------------------------------------------
154 * Configure the output e.g. WholeExtent, spacing, origin, scalar type...
156 void vtkGdcmReader::ExecuteInformation()
158 if(this->MTime>this->fileTime)
160 this->TotalNumberOfPlanes = this->CheckFileCoherence();
161 if ( this->TotalNumberOfPlanes == 0)
163 vtkErrorMacro(<< "File set is not coherent. Exiting...");
167 // if the user has not set the extent, but has set the VOI
168 // set the z axis extent to the VOI z axis
169 if (this->DataExtent[4]==0 && this->DataExtent[5] == 0 &&
170 (this->DataVOI[4] || this->DataVOI[5]))
172 this->DataExtent[4] = this->DataVOI[4];
173 this->DataExtent[5] = this->DataVOI[5];
176 // When the user has set the VOI, check it's coherence with the file content.
177 if (this->DataVOI[0] || this->DataVOI[1] ||
178 this->DataVOI[2] || this->DataVOI[3] ||
179 this->DataVOI[4] || this->DataVOI[5])
181 if ((this->DataVOI[0] < 0) ||
182 (this->DataVOI[1] >= this->NumColumns) ||
183 (this->DataVOI[2] < 0) ||
184 (this->DataVOI[3] >= this->NumLines) ||
185 (this->DataVOI[4] < 0) ||
186 (this->DataVOI[5] >= this->TotalNumberOfPlanes ))
188 vtkWarningMacro(<< "The requested VOI is larger than expected extent.");
189 this->DataVOI[0] = 0;
190 this->DataVOI[1] = this->NumColumns - 1;
191 this->DataVOI[2] = 0;
192 this->DataVOI[3] = this->NumLines - 1;
193 this->DataVOI[4] = 0;
194 this->DataVOI[5] = this->TotalNumberOfPlanes - 1;
198 // Positionate the Extent.
199 this->DataExtent[0] = 0;
200 this->DataExtent[1] = this->NumColumns - 1;
201 this->DataExtent[2] = 0;
202 this->DataExtent[3] = this->NumLines - 1;
203 this->DataExtent[4] = 0;
204 this->DataExtent[5] = this->TotalNumberOfPlanes - 1;
206 // We don't need to positionate the Endian related stuff (by using
207 // this->SetDataByteOrderToBigEndian() or SetDataByteOrderToLittleEndian()
208 // since the reading of the file is done by gdcm.
209 // But we do need to set up the data type for downstream filters:
210 if ( ImageType == "8U" )
212 vtkDebugMacro(<< "8 bits unsigned image");
213 this->SetDataScalarTypeToUnsignedChar();
215 else if ( ImageType == "8S" )
217 vtkErrorMacro(<< "Cannot handle 8 bit signed files");
220 else if ( ImageType == "16U" )
222 vtkDebugMacro(<< "16 bits unsigned image");
223 this->SetDataScalarTypeToUnsignedShort();
225 else if ( ImageType == "16S" )
227 vtkDebugMacro(<< "16 bits signed image");
228 this->SetDataScalarTypeToShort();
230 else if ( ImageType == "32U" )
232 vtkDebugMacro(<< "32 bits unsigned image");
233 vtkDebugMacro(<< "WARNING: forced to signed int !");
234 this->SetDataScalarTypeToInt();
236 else if ( ImageType == "32S" )
238 vtkDebugMacro(<< "32 bits signed image");
239 this->SetDataScalarTypeToInt();
241 else if ( ImageType == "FD" )
243 vtkDebugMacro(<< "64 bits Double image");
244 this->SetDataScalarTypeToDouble();
246 //Set number of scalar components:
247 this->SetNumberOfScalarComponents(this->NumComponents);
249 this->fileTime=this->MTime;
252 this->Superclass::ExecuteInformation();
256 * Update => ouput->Update => UpdateData => Execute => ExecuteData
257 * (see vtkSource.cxx for last step).
258 * This function (redefinition of vtkImageReader::ExecuteData, see
259 * VTK/IO/vtkImageReader.cxx) reads a data from a file. The data
260 * extent/axes are assumed to be the same as the file extent/order.
262 void vtkGdcmReader::ExecuteData(vtkDataObject *output)
264 if (this->InternalFileNameList.empty())
266 vtkErrorMacro(<< "A least a valid FileName must be specified.");
270 // FIXME : extraneous parsing of header is made when allocating OuputData
271 vtkImageData *data = this->AllocateOutputData(output);
272 data->SetExtent(this->DataExtent);
273 data->GetPointData()->GetScalars()->SetName("DicomImage-Volume");
275 // Test if output has valid extent
276 // Prevent memory errors
277 if((this->DataExtent[1]-this->DataExtent[0]>=0) &&
278 (this->DataExtent[3]-this->DataExtent[2]>=0) &&
279 (this->DataExtent[5]-this->DataExtent[4]>=0))
281 // The memory size for a full stack of images of course depends
282 // on the number of planes and the size of each image:
283 //size_t StackNumPixels = this->NumColumns * this->NumLines
284 // * this->TotalNumberOfPlanes * this->NumComponents;
285 //size_t stack_size = StackNumPixels * this->PixelSize; //not used
286 // Allocate pixel data space itself.
288 // Variables for the UpdateProgress. We shall use 50 steps to signify
289 // the advance of the process:
290 unsigned long UpdateProgressTarget = (unsigned long) ceil (this->NumLines
291 * this->TotalNumberOfPlanes
293 // The actual advance measure:
294 unsigned long UpdateProgressCount = 0;
296 // Filling the allocated memory space with each image/volume:
297 unsigned char *Dest = (unsigned char *)data->GetScalarPointer();
298 for (std::list<std::string>::iterator filename = InternalFileNameList.begin();
299 filename != InternalFileNameList.end();
302 // Images that were tagged as unreadable in CheckFileCoherence()
303 // are substituted with a black image to let the caller visually
304 // notice something wrong is going on:
305 if (*filename != "GDCM_UNREADABLE")
307 // Update progress related for good files is made in LoadImageInMemory
308 Dest += this->LoadImageInMemory(*filename, Dest,
309 UpdateProgressTarget,
310 UpdateProgressCount);
314 // We insert a black image in the stack for the user to be aware that
315 // this image/volume couldn't be loaded. We simply skip one image
317 Dest += this->NumColumns * this->NumLines * this->PixelSize;
319 // Update progress related for bad files:
320 UpdateProgressCount += this->NumLines;
321 if (UpdateProgressTarget > 0)
323 if (!(UpdateProgressCount%UpdateProgressTarget))
325 this->UpdateProgress(UpdateProgressCount/(50.0*UpdateProgressTarget));
328 } // Else, file not loadable
334 * vtkGdcmReader can have the file names specified through two ways:
335 * (1) by calling the vtkImageReader2::SetFileName(), SetFilePrefix() and
337 * (2) By successive calls to vtkGdcmReader::AddFileName()
338 * When the first method was used by caller we need to update the local
341 void vtkGdcmReader::BuildFileListFromPattern()
343 this->RemoveAllInternalFileName();
345 if ((! this->FileNameList.empty()) && this->FileName )
347 vtkErrorMacro(<< "Both AddFileName and SetFileName schemes were used");
348 vtkErrorMacro(<< "No images loaded ! ");
352 if ((! this->FileNameList.empty()) && this->FilePrefix )
354 vtkErrorMacro(<< "Both AddFileName and SetFilePrefix schemes were used");
355 vtkErrorMacro(<< "No images loaded ! ");
359 if (this->FileName && this->FilePrefix)
361 vtkErrorMacro(<< "Both SetFileName and SetFilePrefix schemes were used");
362 vtkErrorMacro(<< "No images loaded ! ");
366 if (! this->FileNameList.empty() )
368 vtkDebugMacro(<< "Using the AddFileName specified files");
369 this->InternalFileNameList=this->FileNameList;
373 if (!this->FileName && !this->FilePrefix)
375 vtkErrorMacro(<< "FileNames are not set. Either use AddFileName() or");
376 vtkErrorMacro(<< "specify a FileName or FilePrefix.");
382 // Single file loading (as given with ::SetFileName()):
383 // Case of multi-frame file considered here
384 this->ComputeInternalFileName(this->DataExtent[4]);
385 vtkDebugMacro(<< "Adding file " << this->InternalFileName);
386 this->AddInternalFileName(this->InternalFileName);
390 // Multi file loading (as given with ::SetFilePattern()):
391 for (int idx = this->DataExtent[4]; idx <= this->DataExtent[5]; ++idx)
393 this->ComputeInternalFileName(idx);
394 vtkDebugMacro(<< "Adding file " << this->InternalFileName);
395 this->AddInternalFileName(this->InternalFileName);
401 * When more than one filename is specified (i.e. we expect loading
402 * a stack or volume) we need to check that the corresponding images/volumes
403 * to be loaded are coherent i.e. to make sure:
404 * - they all share the same X dimensions
405 * - they all share the same Y dimensions
406 * - they all share the same ImageType ( 8 bit signed, or unsigned...)
408 * Eventually, we emit a warning when all the files do NOT share the
409 * Z dimension, since we can still build a stack but the
410 * files are not coherent in Z, which is probably a source a trouble...
411 * When files are not readable (either the file cannot be opened or
412 * because gdcm cannot parse it), they are flagged as "GDCM_UNREADABLE".
413 * This method returns the total number of planar images to be loaded
414 * (i.e. an image represents one plane, but a volume represents many planes)
416 int vtkGdcmReader::CheckFileCoherence()
418 int ReturnedTotalNumberOfPlanes = 0; // The returned value.
420 this->BuildFileListFromPattern();
421 if (this->InternalFileNameList.empty())
423 vtkErrorMacro(<< "FileNames are not set.");
427 bool FoundReferenceFile = false;
430 // Loop on the filenames:
431 // - check for their existence and gdcm "parsability"
432 // - get the coherence check done:
433 for (std::list<std::string>::iterator filename = InternalFileNameList.begin();
434 filename != InternalFileNameList.end();
437 // The file is always added in the number of planes
438 // - If file doesn't exist, it will be replaced by a black plane in the
439 // ExecuteData method
440 // - If file has more than 1 plane, other planes will be added later to
441 // to the ReturnedTotalNumberOfPlanes variable counter
442 ReturnedTotalNumberOfPlanes += 1;
444 /////// Stage 0: check for file name:
445 if(*filename == std::string("GDCM_UNREADABLE"))
448 /////// Stage 1: check for file readability:
449 // Stage 1.1: check for file existence.
451 fp = fopen(filename->c_str(),"rb");
454 vtkErrorMacro(<< "Unable to open file " << filename->c_str());
455 vtkErrorMacro(<< "Removing this file from readed files "
456 << filename->c_str());
457 *filename = "GDCM_UNREADABLE";
462 // Stage 1.2: check for Gdcm parsability
463 gdcm::File GdcmFile(filename->c_str() );
464 if (!GdcmFile.IsReadable())
466 vtkErrorMacro(<< "Gdcm cannot parse file " << filename->c_str());
467 vtkErrorMacro(<< "Removing this file from readed files "
468 << filename->c_str());
469 *filename = "GDCM_UNREADABLE";
473 // Stage 1.3: further gdcm compatibility on PixelType
474 std::string type = GdcmFile.GetPixelType();
475 if ( (type != "8U") && (type != "8S")
476 && (type != "16U") && (type != "16S")
477 && (type != "32U") && (type != "32S") )
479 vtkErrorMacro(<< "Bad File Type for file " << filename->c_str() << "\n"
480 << " File type found : " << type.c_str()
481 << " (might be 8U, 8S, 16U, 16S, 32U, 32S) \n"
482 << " Removing this file from readed files");
483 *filename = "GDCM_UNREADABLE";
487 // Stage 2: check coherence of the set of files
488 int NX = GdcmFile.GetXSize();
489 int NY = GdcmFile.GetYSize();
490 int NZ = GdcmFile.GetZSize();
491 if (FoundReferenceFile)
493 // Stage 2.1: mandatory coherence stage:
494 if ( ( NX != this->NumColumns )
495 || ( NY != this->NumLines )
496 || ( type != this->ImageType ) )
498 vtkErrorMacro(<< "This file is not coherent with previous ones"
499 << filename->c_str());
500 vtkErrorMacro(<< "Removing this file from readed files "
501 << filename->c_str());
502 *filename = "GDCM_UNREADABLE";
506 // Stage 2.2: optional coherence stage
507 if ( NZ != ReferenceNZ )
509 vtkErrorMacro(<< "File is not coherent in Z with previous ones"
510 << filename->c_str());
514 vtkDebugMacro(<< "File is coherent with previous ones"
515 << filename->c_str());
518 // Stage 2.3: when the file contains a volume (as opposed to an image),
519 // notify the caller.
522 vtkErrorMacro(<< "This file contains multiple planes (images)"
523 << filename->c_str());
526 // Eventually, this file can be added on the stack. Update the
527 // full size of the stack
528 vtkDebugMacro("Number of planes added to the stack: " << NZ);
529 ReturnedTotalNumberOfPlanes += NZ - 1; // First plane already added
535 // We didn't have a workable reference file yet.
536 // Set this one as the reference.
537 FoundReferenceFile = true;
538 vtkDebugMacro(<< "This file taken as coherence reference:"
539 << filename->c_str());
540 vtkDebugMacro(<< "Image dimension of reference file as read from Gdcm:"
541 << NX << " " << NY << " " << NZ);
542 vtkDebugMacro(<< "Number of planes added to the stack: " << NZ);
543 // Set aside the size of the image
544 this->NumColumns = NX;
547 ReturnedTotalNumberOfPlanes += NZ - 1; // First plane already added
548 this->ImageType = type;
549 this->PixelSize = GdcmFile.GetPixelSize();
551 if( GdcmFile.HasLUT() && this->AllowLookupTable )
553 // I could raise an error is AllowLookupTable is on and HasLUT() off
554 this->NumComponents = GdcmFile.GetNumberOfScalarComponentsRaw();
558 this->NumComponents = GdcmFile.GetNumberOfScalarComponents(); //rgb or mono
562 this->DataSpacing[0] = GdcmFile.GetXSpacing();
563 this->DataSpacing[1] = GdcmFile.GetYSpacing();
564 this->DataSpacing[2] = GdcmFile.GetZSpacing();
567 //this->DataOrigin[0] = GdcmFile.GetXOrigin();
568 //this->DataOrigin[1] = GdcmFile.GetYOrigin();
569 //this->DataOrigin[2] = GdcmFile.GetZOrigin();
572 } // End of loop on filename
574 ///////// The files we CANNOT load are flaged. On debugging purposes
575 // count the loadable number of files and display their number:
576 int NumberCoherentFiles = 0;
577 for (std::list<std::string>::iterator it = InternalFileNameList.begin();
578 it != InternalFileNameList.end();
581 if (*it != "GDCM_UNREADABLE")
583 NumberCoherentFiles++;
586 vtkDebugMacro(<< "Number of coherent files: " << NumberCoherentFiles);
588 if (ReturnedTotalNumberOfPlanes == 0)
590 vtkErrorMacro(<< "No loadable file.");
593 vtkDebugMacro(<< "Total number of planes on the stack: "
594 << ReturnedTotalNumberOfPlanes);
596 return ReturnedTotalNumberOfPlanes;
599 //-----------------------------------------------------------------------------
602 * Remove all file names to the internal list of images to read.
604 void vtkGdcmReader::RemoveAllInternalFileName(void)
606 this->InternalFileNameList.clear();
610 * Adds a file name to the internal list of images to read.
612 void vtkGdcmReader::AddInternalFileName(const char* name)
614 char * LocalName = new char[strlen(name) + 1];
615 strcpy(LocalName, name);
616 this->InternalFileNameList.push_back(LocalName);
621 * Loads the contents of the image/volume contained by Filename at
622 * the Dest memory address. Returns the size of the data loaded.
624 size_t vtkGdcmReader::LoadImageInMemory(
625 std::string fileName,
627 const unsigned long updateProgressTarget,
628 unsigned long & updateProgressCount)
630 vtkDebugMacro(<< "Copying to memory image [" << fileName.c_str() << "]");
631 gdcm::FileHelper file( fileName.c_str() );
634 // If the data structure of vtk for image/volume representation
635 // were straigthforwards the following would be enough:
636 // GdcmFile.GetImageDataIntoVector((void*)Dest, size);
637 // But vtk chooses to invert the lines of an image, that is the last
638 // line comes first (for some axis related reasons?). Hence we need
639 // to load the image line by line, starting from the end.
641 int numColumns = file.GetFile()->GetXSize();
642 int numLines = file.GetFile()->GetYSize();
643 int numPlanes = file.GetFile()->GetZSize();
644 int lineSize = NumComponents * numColumns * file.GetFile()->GetPixelSize();
645 int planeSize = lineSize * numLines;
649 if( file.GetFile()->HasLUT() && AllowLookupTable )
651 size = file.GetImageDataSize();
652 src = (unsigned char*) file.GetImageDataRaw();
653 unsigned char *lut = (unsigned char*) file.GetLutRGBA();
655 if(!this->LookupTable)
657 this->LookupTable = vtkLookupTable::New();
660 this->LookupTable->SetNumberOfTableValues(256);
661 for (int tmp=0; tmp<256; tmp++)
663 this->LookupTable->SetTableValue(tmp,
664 (float)lut[4*tmp+0]/255.0,
665 (float)lut[4*tmp+1]/255.0,
666 (float)lut[4*tmp+2]/255.0,
669 this->LookupTable->SetRange(0,255);
670 vtkDataSetAttributes *a = this->GetOutput()->GetPointData();
671 a->GetScalars()->SetLookupTable(this->LookupTable);
676 size = file.GetImageDataSize();
677 src = (unsigned char*)file.GetImageData();
680 unsigned char *dst = dest + planeSize - lineSize;
681 for (int plane = 0; plane < numPlanes; plane++)
683 for (int line = 0; line < numLines; line++)
685 // Copy one line at proper destination:
686 memcpy((void*)dst, (void*)src, lineSize);
689 // Update progress related:
690 if (!(updateProgressCount%updateProgressTarget))
692 this->UpdateProgress(updateProgressCount/(50.0*updateProgressTarget));
694 updateProgressCount++;
696 dst += 2 * planeSize;
702 //-----------------------------------------------------------------------------