1 /*=========================================================================
4 Module: $RCSfile: vtkGdcmReader.cxx,v $
6 Date: $Date: 2005/08/31 08:28:32 $
7 Version: $Revision: 1.80 $
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 // //////////////////////////////////////////////////////////////
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 :
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);
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
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);
54 // WARNING TODO CLEANME
55 // Actual limitations of this code
56 // when a Coherent File List from SerieHelper is not used (bad idea :-(
58 // //////////////////////////////////////////////////////////////
60 #include "gdcmFileHelper.h"
63 #include "vtkGdcmReader.h"
64 #include "gdcmDebug.h"
65 #include "gdcmCommon.h"
67 #include <vtkObjectFactory.h>
68 #include <vtkImageData.h>
69 #include <vtkPointData.h>
70 #include <vtkLookupTable.h>
72 vtkCxxRevisionMacro(vtkGdcmReader, "$Revision: 1.80 $")
73 vtkStandardNewMacro(vtkGdcmReader)
75 //-----------------------------------------------------------------------------
76 // Constructor / Destructor
77 vtkGdcmReader::vtkGdcmReader()
79 this->LookupTable = NULL;
80 this->AllowLookupTable = false;
81 this->AllowLightChecking = false;
82 this->LoadMode = gdcm::LD_ALL; // Load everything (possible values :
86 this->CoherentFileList = 0;
87 this->UserFunction = 0;
90 this->Execution=false;
93 vtkGdcmReader::~vtkGdcmReader()
95 this->RemoveAllFileName();
96 this->InternalFileNameList.clear();
98 this->LookupTable->Delete();
101 //-----------------------------------------------------------------------------
103 void vtkGdcmReader::PrintSelf(ostream &os, vtkIndent indent)
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();
112 os << nextIndent << it->c_str() << endl ;
116 //-----------------------------------------------------------------------------
119 * Remove all files from the list of images to read.
121 void vtkGdcmReader::RemoveAllFileName(void)
123 this->FileNameList.clear();
128 * Adds a file name to the list of images to read.
130 void vtkGdcmReader::AddFileName(const char* name)
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);
139 * Sets up a filename to be read.
141 void vtkGdcmReader::SetFileName(const char *name)
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();
152 //-----------------------------------------------------------------------------
155 * Configure the output e.g. WholeExtent, spacing, origin, scalar type...
157 void vtkGdcmReader::ExecuteInformation()
162 this->Execution=true;
163 this->RemoveAllInternalFile();
164 if(this->MTime>this->fileTime)
166 this->TotalNumberOfPlanes = 0;
168 if ( this->CoherentFileList != 0 )
170 this->UpdateFileInformation();
174 this->BuildFileListFromPattern();
175 this->LoadFileInformation();
178 if ( this->TotalNumberOfPlanes == 0)
180 vtkErrorMacro(<< "File set is not coherent. Exiting...");
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]))
189 this->DataExtent[4] = this->DataVOI[4];
190 this->DataExtent[5] = this->DataVOI[5];
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])
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 ))
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;
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;
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" )
229 vtkDebugMacro(<< "8 bits unsigned image");
230 this->SetDataScalarTypeToUnsignedChar();
232 else if ( ImageType == "8S" )
234 vtkErrorMacro(<< "Cannot handle 8 bit signed files");
237 else if ( ImageType == "16U" )
239 vtkDebugMacro(<< "16 bits unsigned image");
240 this->SetDataScalarTypeToUnsignedShort();
242 else if ( ImageType == "16S" )
244 vtkDebugMacro(<< "16 bits signed image");
245 this->SetDataScalarTypeToShort();
247 else if ( ImageType == "32U" )
249 vtkDebugMacro(<< "32 bits unsigned image");
250 vtkDebugMacro(<< "WARNING: forced to signed int !");
251 this->SetDataScalarTypeToInt();
253 else if ( ImageType == "32S" )
255 vtkDebugMacro(<< "32 bits signed image");
256 this->SetDataScalarTypeToInt();
258 else if ( ImageType == "FD" )
260 vtkDebugMacro(<< "64 bits Double image");
261 this->SetDataScalarTypeToDouble();
263 //Set number of scalar components:
264 this->SetNumberOfScalarComponents(this->NumComponents);
266 this->fileTime=this->MTime;
269 this->Superclass::ExecuteInformation();
271 this->GetOutput()->SetUpdateExtentToWholeExtent();
272 this->BuildData(this->GetOutput());
274 this->Execution=false;
275 this->RemoveAllInternalFile();
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.
285 void vtkGdcmReader::ExecuteData(vtkDataObject *output)
287 vtkImageData *data=vtkImageData::SafeDownCast(output);
288 data->SetExtent(this->DataExtent);
290 /* if ( CoherentFileList != 0 ) // When a list of names is passed
292 if (this->CoherentFileList->empty())
294 vtkErrorMacro(<< "Coherent File List must have at least a valid File*.");
298 else if (this->InternalFileNameList.empty())
300 vtkErrorMacro(<< "A least a valid FileName must be specified.");
306 void vtkGdcmReader::BuildData(vtkDataObject *output)
308 vtkImageData *data = this->AllocateOutputData(output);
310 data->GetPointData()->GetScalars()->SetName("DicomImage-Volume");
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))
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.
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
330 // The actual advance measure:
331 unsigned long UpdateProgressCount = 0;
333 // Filling the allocated memory space with each image/volume:
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();
342 this->LoadImageInMemory(*it, Dest,
343 UpdateProgressTarget,
344 UpdateProgressCount);
351 * vtkGdcmReader can have the file names specified through two ways:
352 * (1) by calling the vtkImageReader2::SetFileName(), SetFilePrefix() and
354 * (2) By successive calls to vtkGdcmReader::AddFileName()
355 * When the first method was used by caller we need to update the local
358 void vtkGdcmReader::BuildFileListFromPattern()
360 this->RemoveAllInternalFileName();
362 // Test miscellanous cases
363 if ((! this->FileNameList.empty()) && this->FileName )
365 vtkErrorMacro(<< "Both AddFileName and SetFileName schemes were used");
366 vtkErrorMacro(<< "No images loaded ! ");
370 if ((! this->FileNameList.empty()) && this->FilePrefix )
372 vtkErrorMacro(<< "Both AddFileName and SetFilePrefix schemes were used");
373 vtkErrorMacro(<< "No images loaded ! ");
377 if (this->FileName && this->FilePrefix)
379 vtkErrorMacro(<< "Both SetFileName and SetFilePrefix schemes were used");
380 vtkErrorMacro(<< "No images loaded ! ");
384 // Create the InternalFileNameList
385 if (! this->FileNameList.empty() )
387 vtkDebugMacro(<< "Using the AddFileName specified files");
388 this->InternalFileNameList=this->FileNameList;
392 if (!this->FileName && !this->FilePrefix)
394 vtkErrorMacro(<< "FileNames are not set. Either use AddFileName() or");
395 vtkErrorMacro(<< "specify a FileName or FilePrefix.");
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);
409 // Multi file loading (as given with ::SetFilePattern()):
410 for (int idx = this->DataExtent[4]; idx <= this->DataExtent[5]; ++idx)
412 this->ComputeInternalFileName(idx);
413 vtkDebugMacro(<< "Adding file " << this->InternalFileName);
414 this->AddInternalFileName(this->InternalFileName);
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
426 * The source of this work is the list of file name generated by the
427 * BuildFileListFromPattern method
429 void vtkGdcmReader::LoadFileInformation()
432 bool foundReference=false;
436 for (std::list<std::string>::iterator filename = InternalFileNameList.begin();
437 filename != InternalFileNameList.end();
440 // check for file readability
442 fp = fopen(filename->c_str(),"rb");
445 vtkErrorMacro(<< "Unable to open file " << filename->c_str());
446 vtkErrorMacro(<< "Removing this file from read files: "
447 << filename->c_str());
449 InternalFileList.push_back(file);
455 file=new gdcm::File();
456 file->SetLoadMode( LoadMode );
457 file->SetFileName(filename->c_str() );
460 // Test the Dicom file readability
461 if(!file->IsReadable())
463 vtkErrorMacro(<< "Gdcm cannot parse file " << filename->c_str());
464 vtkErrorMacro(<< "Removing this file from read files: "
465 << filename->c_str());
468 InternalFileList.push_back(file);
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") )
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");
484 InternalFileList.push_back(file);
488 // Test the image informations
491 foundReference = true;
492 GetFileInformation(file);
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 << " "
500 else if(!TestFileInformation(file))
506 InternalFileList.push_back(file);
511 * Update the file informations.
512 * This works exactly like LoadFileInformation, but the source of work
513 * is the list of coherent files
515 void vtkGdcmReader::UpdateFileInformation()
517 this->InternalFileList=*(this->CoherentFileList);
520 for(gdcmFileList::iterator it=InternalFileList.begin();
521 it!=InternalFileList.end();
526 GetFileInformation(*it);
533 * Get the informations from a file.
534 * These informations are required to specify the output image
537 void vtkGdcmReader::GetFileInformation(gdcm::File *file)
539 // Get the image caracteristics
540 this->NumColumns = file->GetXSize();
541 this->NumLines = file->GetYSize();
542 this->NumPlanes = file->GetZSize();
544 if (CoherentFileList == 0)
545 this->TotalNumberOfPlanes = this->NumPlanes*InternalFileNameList.size();
547 this->TotalNumberOfPlanes = this->NumPlanes*CoherentFileList->size();
549 this->ImageType = file->GetPixelType();
550 this->PixelSize = file->GetPixelSize();
552 this->DataSpacing[0] = file->GetXSpacing();
553 this->DataSpacing[1] = file->GetYSpacing();
554 this->DataSpacing[2] = file->GetZSpacing();
556 // Get the image data caracteristics
557 if( file->HasLUT() && this->AllowLookupTable )
559 // I could raise an error is AllowLookupTable is on and HasLUT() off
560 this->NumComponents = file->GetNumberOfScalarComponentsRaw();
564 this->NumComponents = file->GetNumberOfScalarComponents(); //rgb or mono
569 * When more than one filename is specified (i.e. we expect loading
570 * a stack or volume) we need to check that the corresponding images/volumes
571 * to be loaded are coherent i.e. to make sure:
572 * - they all share the same X dimensions
573 * - they all share the same Y dimensions
574 * - they all share the same ImageType ( 8 bit signed, or unsigned...)
576 * Eventually, we emit a warning when all the files do NOT share the
577 * Z dimension, since we can still build a stack but the
578 * files are not coherent in Z, which is probably a source a trouble...
579 * When files are not readable (either the file cannot be opened or
580 * because gdcm cannot parse it), they are flagged as "GDCM_UNREADABLE".
581 * This method returns the total number of planar images to be loaded
582 * (i.e. an image represents one plane, but a volume represents many planes)
585 * Test the coherent informations of the file with the reference informations
586 * used as image caracteristics. The tested informations are :
587 * - they all share the same X dimensions
588 * - they all share the same Y dimensions
589 * - they all share the same Z dimensions
590 * - they all share the same number of components
591 * - they all share the same ImageType ( 8 bit signed, or unsigned...)
593 * \return True if the file match, False otherwise
595 bool vtkGdcmReader::TestFileInformation(gdcm::File *file)
597 int numColumns = file->GetXSize();
598 int numLines = file->GetYSize();
599 int numPlanes = file->GetZSize();
601 unsigned int pixelSize = file->GetPixelSize();
603 if( file->HasLUT() && this->AllowLookupTable )
604 numComponents = file->GetNumberOfScalarComponentsRaw();
606 numComponents = file->GetNumberOfScalarComponents(); //rgb or mono
608 if( numColumns != this->NumColumns )
610 vtkErrorMacro(<< "File X value doesn't match with the previous ones: "
611 << file->GetFileName().c_str()
612 << ". Found " << numColumns << ", must be "
613 << this->NumColumns);
616 if( numLines != this->NumLines )
618 vtkErrorMacro(<< "File Y value doesn't match with the previous ones: "
619 << file->GetFileName().c_str()
620 << ". Found " << numLines << ", must be "
624 if( numPlanes != this->NumPlanes )
626 vtkErrorMacro(<< "File Z value doesn't match with the previous ones: "
627 << file->GetFileName().c_str()
628 << ". Found " << numPlanes << ", must be "
632 if( numComponents != this->NumComponents )
634 vtkErrorMacro(<< "File Components count doesn't match with the previous ones: "
635 << file->GetFileName().c_str()
636 << ". Found " << numComponents << ", must be "
637 << this->NumComponents);
640 if( pixelSize != this->PixelSize )
642 vtkErrorMacro(<< "File pixel size doesn't match with the previous ones: "
643 << file->GetFileName().c_str()
644 << ". Found " << pixelSize << ", must be "
652 //-----------------------------------------------------------------------------
655 * Remove all file names to the internal list of images to read.
657 void vtkGdcmReader::RemoveAllInternalFileName(void)
659 this->InternalFileNameList.clear();
663 * Adds a file name to the internal list of images to read.
665 void vtkGdcmReader::AddInternalFileName(const char *name)
667 char *LocalName = new char[strlen(name) + 1];
668 strcpy(LocalName, name);
669 this->InternalFileNameList.push_back(LocalName);
674 * Remove all file names to the internal list of images to read.
676 void vtkGdcmReader::RemoveAllInternalFile(void)
680 for(gdcmFileList::iterator it=InternalFileList.begin();
681 it!=InternalFileList.end();
687 this->InternalFileList.clear();
690 void vtkGdcmReader::IncrementProgress(const unsigned long updateProgressTarget,
691 unsigned long &updateProgressCount)
693 // Update progress related for bad files:
694 updateProgressCount += this->NumLines;
695 if (updateProgressTarget > 0)
697 if (!(updateProgressCount%updateProgressTarget))
699 this->UpdateProgress(updateProgressCount/(50.0*updateProgressTarget));
705 * Loads the contents of the image/volume contained by char *fileName at
706 * the dest memory address. Returns the size of the data loaded.
708 /*void vtkGdcmReader::LoadImageInMemory(
709 std::string fileName,
711 const unsigned long updateProgressTarget,
712 unsigned long &updateProgressCount)
714 vtkDebugMacro(<< "Copying to memory image [" << fileName.c_str() << "]");
717 f = new gdcm::File();
718 f->SetLoadMode( LoadMode );
719 f->SetFileName( fileName.c_str() );
722 LoadImageInMemory(f,dest,
723 updateProgressTarget,
724 updateProgressCount);
729 * Loads the contents of the image/volume contained by gdcm::File* f at
730 * the Dest memory address. Returns the size of the data loaded.
731 * \ param f File to consider. NULL if the file must be skiped
732 * \remarks Assume that if (f != NULL) then its caracteristics match
733 * with the previous ones
735 void vtkGdcmReader::LoadImageInMemory(
738 const unsigned long updateProgressTarget,
739 unsigned long &updateProgressCount)
744 gdcm::FileHelper *fileH = new gdcm::FileHelper( f );
745 fileH->SetUserFunction( UserFunction );
747 int numColumns = f->GetXSize();
748 int numLines = f->GetYSize();
749 int numPlanes = f->GetZSize();
752 if( f->HasLUT() && this->AllowLookupTable )
753 numComponents = f->GetNumberOfScalarComponentsRaw();
755 numComponents = f->GetNumberOfScalarComponents(); //rgb or mono
757 vtkDebugMacro(<< "Copying to memory image [" << f->GetFileName().c_str() << "]");
760 // If the data structure of vtk for image/volume representation
761 // were straigthforwards the following would be enough:
762 // GdcmFile.GetImageDataIntoVector((void*)Dest, size);
763 // But vtk chooses to invert the lines of an image, that is the last
764 // line comes first (for some axis related reasons?). Hence we need
765 // to load the image line by line, starting from the end.
767 int lineSize = NumComponents * numColumns * f->GetPixelSize();
768 int planeSize = lineSize * numLines;
772 if( fileH->GetFile()->HasLUT() && AllowLookupTable )
774 size = fileH->GetImageDataSize();
775 src = (unsigned char*) fileH->GetImageDataRaw();
776 unsigned char *lut = (unsigned char*) fileH->GetLutRGBA();
778 if(!this->LookupTable)
780 this->LookupTable = vtkLookupTable::New();
783 this->LookupTable->SetNumberOfTableValues(256);
784 for (int tmp=0; tmp<256; tmp++)
786 this->LookupTable->SetTableValue(tmp,
787 (float)lut[4*tmp+0]/255.0,
788 (float)lut[4*tmp+1]/255.0,
789 (float)lut[4*tmp+2]/255.0,
792 this->LookupTable->SetRange(0,255);
793 vtkDataSetAttributes *a = this->GetOutput()->GetPointData();
794 a->GetScalars()->SetLookupTable(this->LookupTable);
799 size = fileH->GetImageDataSize();
800 src = (unsigned char*)fileH->GetImageData();
803 unsigned char *dst = dest + planeSize - lineSize;
804 for (int plane = 0; plane < numPlanes; plane++)
806 for (int line = 0; line < numLines; line++)
808 // Copy one line at proper destination:
809 memcpy((void*)dst, (void*)src, lineSize);
812 // Update progress related:
813 if (!(updateProgressCount%updateProgressTarget))
815 this->UpdateProgress(updateProgressCount/(50.0*updateProgressTarget));
817 updateProgressCount++;
819 dst += 2 * planeSize;
825 //-----------------------------------------------------------------------------