1 /*=========================================================================
4 Module: $RCSfile: vtkGdcmReader.cxx,v $
6 Date: $Date: 2005/07/30 18:31:25 $
7 Version: $Revision: 1.74 $
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 // /////// Redundant and unnecessary header parsing
59 // In it's current state this code actually parses three times the Dicom
60 // header of a file before the corresponding image gets loaded in the
62 // Here is the process:
63 // 1/ First loading happens in ExecuteInformation which, in order to
64 // positionate the vtk extents, calls CheckFileCoherence. The purpose
65 // of CheckFileCoherence is to make sure all the images in the future
66 // stack are "homogenous" (same size, same representation...).
67 // This can only be achieved by parsing all the Dicom headers...
68 // --> to avoid loosing too much time :
69 // If user is 150% sure *all* the files are coherent, that is to say :
70 // they may be open, they are gdcm-readable, they have the same sizes,
71 // they have the same 'pixel' type, they are single frame,
72 // they have the same color convention ...
73 // he may use SetCheckFileCoherenceLight() to request a 'light' coherence
75 // 2/ ExecuteData is then responsible for the next two loadings - 2 ?!?-:
76 // 2a/ ExecuteData calls AllocateOutputData that in turn seems to
77 // (indirectely call) ExecuteInformation which ends up in a second
79 // This is fixed by adding a test at the beginning of ExecuteInformation
80 // on the modification of the object instance. If a modification have been
81 // made (method Modified() ), the MTime value is increased. The fileTime
82 // is compared to this new value to find a modification in the class
84 // 2b/ the core of ExecuteData then needs gdcm::File (which in turns
85 // initializes gdcm::File in the constructor) in order to access
89 // maintain a list of gdcm::Files (created by say ExecuteInformation) created
90 // once and for all accross the life of vtkGdcmFile (it would only load
91 // new gdcm::File if the user changes the list). ExecuteData would then use
92 // those gdcm::File and hence avoid calling the constructor:
93 // - advantage: the header of the files would only be parsed once.
94 // - drawback: once execute information is called (i.e. on creation of
95 // a vtkGdcmFile) the gdcm::File structure is loaded in memory.
96 // The average size of a gdcm::File being of 100Ko,
97 // if oneloads 10 stacks of images with say 200 images each,
98 // you end-up with a loss of 200Mo...
100 // /////// Never unallocated memory:
101 // ExecuteData allocates space for the pixel data [which will get pointed
102 // by the vtkPointData() through the call
103 // data->GetPointData()->GetScalars()->SetVoidArray(mem, StackNumPixels, 0);]
104 // This data is never "freed" neither in the destructor nor when the
105 // filename list is extended, ExecuteData is called a second (or third)
110 // //////////////////////////////////////////////////////////////
112 #include "gdcmFileHelper.h"
113 #include "gdcmFile.h"
114 #include "gdcmDocument.h" // for NO_SEQ
116 #include "vtkGdcmReader.h"
117 #include "gdcmDebug.h"
120 #include <vtkObjectFactory.h>
121 #include <vtkImageData.h>
122 #include <vtkPointData.h>
123 #include <vtkLookupTable.h>
125 vtkCxxRevisionMacro(vtkGdcmReader, "$Revision: 1.74 $");
126 vtkStandardNewMacro(vtkGdcmReader);
128 //-----------------------------------------------------------------------------
129 // Constructor / Destructor
130 vtkGdcmReader::vtkGdcmReader()
132 this->LookupTable = NULL;
133 this->AllowLookupTable = 0;
134 this->LightChecking = false;
135 this->LoadMode = 0; // Load everything (possible values : NO_SEQ, NO_SHADOW,
137 this->CoherentFileList = 0;
138 this->UserFunction = 0;
141 vtkGdcmReader::~vtkGdcmReader()
143 this->RemoveAllFileName();
144 this->InternalFileNameList.clear();
145 if(this->LookupTable)
146 this->LookupTable->Delete();
149 //-----------------------------------------------------------------------------
151 void vtkGdcmReader::PrintSelf(ostream &os, vtkIndent indent)
153 this->Superclass::PrintSelf(os,indent);
154 os << indent << "Filenames : " << endl;
155 vtkIndent nextIndent = indent.GetNextIndent();
156 for (std::list<std::string>::iterator it = FileNameList.begin();
157 it != FileNameList.end();
160 os << nextIndent << it->c_str() << endl ;
164 //-----------------------------------------------------------------------------
167 * Remove all files from the list of images to read.
169 void vtkGdcmReader::RemoveAllFileName(void)
171 this->FileNameList.clear();
176 * Adds a file name to the list of images to read.
178 void vtkGdcmReader::AddFileName(const char* name)
180 // We need to bypass the const pointer [since list<>.push_bash() only
181 // takes a char* (but not a const char*)] by making a local copy:
182 char *LocalName = new char[strlen(name) + 1];
183 strcpy(LocalName, name);
184 this->FileNameList.push_back(LocalName);
190 * Sets up a filename to be read.
192 void vtkGdcmReader::SetFileName(const char *name)
194 vtkImageReader2::SetFileName(name);
195 // Since we maintain a list of filenames, when building a volume,
196 // (see vtkGdcmReader::AddFileName), we additionaly need to purge
197 // this list when we manually positionate the filename.
198 vtkDebugMacro(<< "Clearing all files given with AddFileName");
199 this->FileNameList.clear();
204 * Ask for a 'light' checking -actually : just initializing-
205 *if you are 150% sure *all* the files are coherent
207 void vtkGdcmReader::SetCheckFileCoherenceLight()
209 LightChecking = true;
212 //-----------------------------------------------------------------------------
215 * Configure the output e.g. WholeExtent, spacing, origin, scalar type...
217 void vtkGdcmReader::ExecuteInformation()
219 if(this->MTime>this->fileTime)
221 if ( this->CoherentFileList != 0 )
222 this->TotalNumberOfPlanes = this->CheckFileCoherenceAlreadyDone();
223 else if ( this->LightChecking )
224 this->TotalNumberOfPlanes = this->CheckFileCoherenceLight();
226 this->TotalNumberOfPlanes = this->CheckFileCoherence();
228 if ( this->TotalNumberOfPlanes == 0)
230 vtkErrorMacro(<< "File set is not coherent. Exiting...");
234 // if the user has not set the extent, but has set the VOI
235 // set the z axis extent to the VOI z axis
236 if (this->DataExtent[4]==0 && this->DataExtent[5] == 0 &&
237 (this->DataVOI[4] || this->DataVOI[5]))
239 this->DataExtent[4] = this->DataVOI[4];
240 this->DataExtent[5] = this->DataVOI[5];
243 // When the user has set the VOI, check it's coherence with the file content.
244 if (this->DataVOI[0] || this->DataVOI[1] ||
245 this->DataVOI[2] || this->DataVOI[3] ||
246 this->DataVOI[4] || this->DataVOI[5])
248 if ((this->DataVOI[0] < 0) ||
249 (this->DataVOI[1] >= this->NumColumns) ||
250 (this->DataVOI[2] < 0) ||
251 (this->DataVOI[3] >= this->NumLines) ||
252 (this->DataVOI[4] < 0) ||
253 (this->DataVOI[5] >= this->TotalNumberOfPlanes ))
255 vtkWarningMacro(<< "The requested VOI is larger than expected extent.");
256 this->DataVOI[0] = 0;
257 this->DataVOI[1] = this->NumColumns - 1;
258 this->DataVOI[2] = 0;
259 this->DataVOI[3] = this->NumLines - 1;
260 this->DataVOI[4] = 0;
261 this->DataVOI[5] = this->TotalNumberOfPlanes - 1;
266 this->DataExtent[0] = 0;
267 this->DataExtent[1] = this->NumColumns - 1;
268 this->DataExtent[2] = 0;
269 this->DataExtent[3] = this->NumLines - 1;
270 this->DataExtent[4] = 0;
271 this->DataExtent[5] = this->TotalNumberOfPlanes - 1;
273 // We don't need to set the Endian related stuff (by using
274 // this->SetDataByteOrderToBigEndian() or SetDataByteOrderToLittleEndian()
275 // since the reading of the file is done by gdcm.
276 // But we do need to set up the data type for downstream filters:
277 if ( ImageType == "8U" )
279 vtkDebugMacro(<< "8 bits unsigned image");
280 this->SetDataScalarTypeToUnsignedChar();
282 else if ( ImageType == "8S" )
284 vtkErrorMacro(<< "Cannot handle 8 bit signed files");
287 else if ( ImageType == "16U" )
289 vtkDebugMacro(<< "16 bits unsigned image");
290 this->SetDataScalarTypeToUnsignedShort();
292 else if ( ImageType == "16S" )
294 vtkDebugMacro(<< "16 bits signed image");
295 this->SetDataScalarTypeToShort();
297 else if ( ImageType == "32U" )
299 vtkDebugMacro(<< "32 bits unsigned image");
300 vtkDebugMacro(<< "WARNING: forced to signed int !");
301 this->SetDataScalarTypeToInt();
303 else if ( ImageType == "32S" )
305 vtkDebugMacro(<< "32 bits signed image");
306 this->SetDataScalarTypeToInt();
308 else if ( ImageType == "FD" )
310 vtkDebugMacro(<< "64 bits Double image");
311 this->SetDataScalarTypeToDouble();
313 //Set number of scalar components:
314 this->SetNumberOfScalarComponents(this->NumComponents);
316 this->fileTime=this->MTime;
319 this->Superclass::ExecuteInformation();
323 * Update => ouput->Update => UpdateData => Execute => ExecuteData
324 * (see vtkSource.cxx for last step).
325 * This function (redefinition of vtkImageReader::ExecuteData, see
326 * VTK/IO/vtkImageReader.cxx) reads a data from a file. The data
327 * extent/axes are assumed to be the same as the file extent/order.
329 void vtkGdcmReader::ExecuteData(vtkDataObject *output)
331 if ( CoherentFileList != 0 ) // When a list of names is passed
333 if (this->CoherentFileList->empty())
335 vtkErrorMacro(<< "Coherent File List must have at least a valid File*.");
339 else if (this->InternalFileNameList.empty())
341 vtkErrorMacro(<< "A least a valid FileName must be specified.");
345 // FIXME : extraneous parsing of header is made when allocating OuputData
347 vtkImageData *data = this->AllocateOutputData(output);
348 data->SetExtent(this->DataExtent);
349 data->GetPointData()->GetScalars()->SetName("DicomImage-Volume");
351 // Test if output has valid extent
352 // Prevent memory errors
353 if((this->DataExtent[1]-this->DataExtent[0]>=0) &&
354 (this->DataExtent[3]-this->DataExtent[2]>=0) &&
355 (this->DataExtent[5]-this->DataExtent[4]>=0))
357 // The memory size for a full stack of images of course depends
358 // on the number of planes and the size of each image:
359 //size_t StackNumPixels = this->NumColumns * this->NumLines
360 // * this->TotalNumberOfPlanes * this->NumComponents;
361 //size_t stack_size = StackNumPixels * this->PixelSize; //not used
362 // Allocate pixel data space itself.
364 // Variables for the UpdateProgress. We shall use 50 steps to signify
365 // the advance of the process:
366 unsigned long UpdateProgressTarget = (unsigned long) ceil (this->NumLines
367 * this->TotalNumberOfPlanes
369 // The actual advance measure:
370 unsigned long UpdateProgressCount = 0;
372 // Filling the allocated memory space with each image/volume:
374 unsigned char *Dest = (unsigned char *)data->GetScalarPointer();
376 if ( CoherentFileList == 0 ) // When a list of names is passed
378 for (std::list<std::string>::iterator filename = InternalFileNameList.begin();
379 filename != InternalFileNameList.end();
382 // Images that were tagged as unreadable in CheckFileCoherence()
383 // are substituted with a black image to let the caller visually
384 // notice something wrong is going on:
385 if (*filename != "GDCM_UNREADABLE")
387 // Update progress related for good files is made in LoadImageInMemory
388 Dest += this->LoadImageInMemory(*filename, Dest,
389 UpdateProgressTarget,
390 UpdateProgressCount);
394 // We insert a black image in the stack for the user to be aware that
395 // this image/volume couldn't be loaded. We simply skip one image
397 Dest += this->NumColumns * this->NumLines * this->PixelSize;
399 // Update progress related for bad files:
400 UpdateProgressCount += this->NumLines;
401 if (UpdateProgressTarget > 0)
403 if (!(UpdateProgressCount%UpdateProgressTarget))
405 this->UpdateProgress(UpdateProgressCount/(50.0*UpdateProgressTarget));
408 } // Else, file not loadable
412 else // when a Coherent File List is passed
414 for (std::vector<gdcm::File* >::iterator it = CoherentFileList->begin();
415 it != CoherentFileList->end();
419 //std::cout <<"----------------- " << (*it)->GetFileName() << std::endl;
421 Dest += this->LoadImageInMemory(*it, Dest,
422 UpdateProgressTarget,
423 UpdateProgressCount);
424 // Update progress related for bad files:
425 UpdateProgressCount += this->NumLines;
426 if (UpdateProgressTarget > 0)
428 if (!(UpdateProgressCount%UpdateProgressTarget))
430 this->UpdateProgress(UpdateProgressCount/(50.0*UpdateProgressTarget));
440 * vtkGdcmReader can have the file names specified through two ways:
441 * (1) by calling the vtkImageReader2::SetFileName(), SetFilePrefix() and
443 * (2) By successive calls to vtkGdcmReader::AddFileName()
444 * When the first method was used by caller we need to update the local
447 void vtkGdcmReader::BuildFileListFromPattern()
449 this->RemoveAllInternalFileName();
451 if ((! this->FileNameList.empty()) && this->FileName )
453 vtkErrorMacro(<< "Both AddFileName and SetFileName schemes were used");
454 vtkErrorMacro(<< "No images loaded ! ");
458 if ((! this->FileNameList.empty()) && this->FilePrefix )
460 vtkErrorMacro(<< "Both AddFileName and SetFilePrefix schemes were used");
461 vtkErrorMacro(<< "No images loaded ! ");
465 if (this->FileName && this->FilePrefix)
467 vtkErrorMacro(<< "Both SetFileName and SetFilePrefix schemes were used");
468 vtkErrorMacro(<< "No images loaded ! ");
472 if (! this->FileNameList.empty() )
474 vtkDebugMacro(<< "Using the AddFileName specified files");
475 this->InternalFileNameList=this->FileNameList;
479 if (!this->FileName && !this->FilePrefix)
481 vtkErrorMacro(<< "FileNames are not set. Either use AddFileName() or");
482 vtkErrorMacro(<< "specify a FileName or FilePrefix.");
488 // Single file loading (as given with ::SetFileName()):
489 // Case of multi-frame file considered here
490 this->ComputeInternalFileName(this->DataExtent[4]);
491 vtkDebugMacro(<< "Adding file " << this->InternalFileName);
492 this->AddInternalFileName(this->InternalFileName);
496 // Multi file loading (as given with ::SetFilePattern()):
497 for (int idx = this->DataExtent[4]; idx <= this->DataExtent[5]; ++idx)
499 this->ComputeInternalFileName(idx);
500 vtkDebugMacro(<< "Adding file " << this->InternalFileName);
501 this->AddInternalFileName(this->InternalFileName);
507 * When more than one filename is specified (i.e. we expect loading
508 * a stack or volume) we need to check that the corresponding images/volumes
509 * to be loaded are coherent i.e. to make sure:
510 * - they all share the same X dimensions
511 * - they all share the same Y dimensions
512 * - they all share the same ImageType ( 8 bit signed, or unsigned...)
514 * Eventually, we emit a warning when all the files do NOT share the
515 * Z dimension, since we can still build a stack but the
516 * files are not coherent in Z, which is probably a source a trouble...
517 * When files are not readable (either the file cannot be opened or
518 * because gdcm cannot parse it), they are flagged as "GDCM_UNREADABLE".
519 * This method returns the total number of planar images to be loaded
520 * (i.e. an image represents one plane, but a volume represents many planes)
522 int vtkGdcmReader::CheckFileCoherence()
524 int ReturnedTotalNumberOfPlanes = 0; // The returned value.
526 this->BuildFileListFromPattern();
527 if (this->InternalFileNameList.empty())
529 vtkErrorMacro(<< "FileNames are not set.");
533 bool FoundReferenceFile = false;
536 // Loop on the filenames:
537 // - check for their existence and gdcm "parsability"
538 // - get the coherence check done:
539 for (std::list<std::string>::iterator filename = InternalFileNameList.begin();
540 filename != InternalFileNameList.end();
543 // The file is always added in the number of planes
544 // - If file doesn't exist, it will be replaced by a black plane in the
545 // ExecuteData method
546 // - If file has more than 1 plane, other planes will be added later to
547 // to the ReturnedTotalNumberOfPlanes variable counter
548 ReturnedTotalNumberOfPlanes += 1;
550 /////// Stage 0: check for file name:
552 // fixme : how can the filename be equal to "GDCM_UNREADABLE"
555 if(*filename == std::string("GDCM_UNREADABLE"))
558 /////// Stage 1: check for file readability:
559 // Stage 1.1: check for file existence.
561 fp = fopen(filename->c_str(),"rb");
564 vtkErrorMacro(<< "Unable to open file " << filename->c_str());
565 vtkErrorMacro(<< "Removing this file from read files: "
566 << filename->c_str());
567 *filename = "GDCM_UNREADABLE";
572 // Stage 1.2: check for Gdcm parsability
574 // to save some parsing time.
576 GdcmFile.SetLoadMode( LoadMode );
577 GdcmFile.SetFileName(filename->c_str() );
579 if (!GdcmFile.IsReadable())
581 vtkErrorMacro(<< "Gdcm cannot parse file " << filename->c_str());
582 vtkErrorMacro(<< "Removing this file from read files: "
583 << filename->c_str());
584 *filename = "GDCM_UNREADABLE";
588 // Stage 1.3: further gdcm compatibility on PixelType
589 std::string type = GdcmFile.GetPixelType();
590 if ( (type != "8U") && (type != "8S")
591 && (type != "16U") && (type != "16S")
592 && (type != "32U") && (type != "32S") )
594 vtkErrorMacro(<< "Bad File Type for file " << filename->c_str() << "\n"
595 << " File type found : " << type.c_str()
596 << " (might be 8U, 8S, 16U, 16S, 32U, 32S) \n"
597 << " Removing this file from read files");
598 *filename = "GDCM_UNREADABLE";
602 // Stage 2: check coherence of the set of files
603 int NX = GdcmFile.GetXSize();
604 int NY = GdcmFile.GetYSize();
605 int NZ = GdcmFile.GetZSize();
606 if (FoundReferenceFile)
608 // Stage 2.1: mandatory coherence stage:
609 if ( ( NX != this->NumColumns )
610 || ( NY != this->NumLines )
611 || ( type != this->ImageType ) )
613 vtkErrorMacro(<< "This file is not coherent with previous ones: "
614 << filename->c_str());
615 vtkErrorMacro(<< "Removing this file from read files: "
616 << filename->c_str());
617 *filename = "GDCM_UNREADABLE";
621 // Stage 2.2: optional coherence stage
622 if ( NZ != ReferenceNZ )
624 vtkErrorMacro(<< "File is not coherent in Z with previous ones: "
625 << filename->c_str());
629 vtkDebugMacro(<< "File is coherent with previous ones: "
630 << filename->c_str());
633 // Stage 2.3: when the file is 'multiframe', notify the caller.
636 vtkErrorMacro(<< "This file is a 'Multiframe' one: "
637 << filename->c_str());
640 // Eventually, this file can be added on the stack. Update the
641 // full size of the stack
642 vtkDebugMacro("Number of planes added to the stack: " << NZ);
643 ReturnedTotalNumberOfPlanes += NZ - 1; // First plane already added
649 // We didn't have a workable reference file yet.
650 // Set this one as the reference.
651 FoundReferenceFile = true;
652 vtkDebugMacro(<< "This file taken as coherence reference:"
653 << filename->c_str());
654 vtkDebugMacro(<< "Image dimensions of reference file as read from Gdcm:"
655 << NX << " " << NY << " " << NZ);
656 vtkDebugMacro(<< "Number of planes added to the stack: " << NZ);
657 // Set aside the size of the image
658 this->NumColumns = NX;
661 ReturnedTotalNumberOfPlanes += NZ - 1; // First plane already added
662 this->ImageType = type;
663 this->PixelSize = GdcmFile.GetPixelSize();
665 if( GdcmFile.HasLUT() && this->AllowLookupTable )
667 // I could raise an error is AllowLookupTable is on and HasLUT() off
668 this->NumComponents = GdcmFile.GetNumberOfScalarComponentsRaw();
672 this->NumComponents = GdcmFile.GetNumberOfScalarComponents(); //rgb or mono
675 this->DataSpacing[0] = GdcmFile.GetXSpacing();
676 this->DataSpacing[1] = GdcmFile.GetYSpacing();
677 this->DataSpacing[2] = GdcmFile.GetZSpacing();
679 } // End of loop on filename
681 ///////// The files we CANNOT load are flaged. On debugging purposes
682 // count the loadable number of files and display their number:
683 int NumberCoherentFiles = 0;
684 for (std::list<std::string>::iterator it = InternalFileNameList.begin();
685 it != InternalFileNameList.end();
688 if (*it != "GDCM_UNREADABLE")
690 NumberCoherentFiles++;
693 vtkDebugMacro(<< "Number of coherent files: " << NumberCoherentFiles);
695 if (ReturnedTotalNumberOfPlanes == 0)
697 vtkErrorMacro(<< "No loadable file.");
700 vtkDebugMacro(<< "Total number of planes on the stack: "
701 << ReturnedTotalNumberOfPlanes);
703 return ReturnedTotalNumberOfPlanes;
706 //-----------------------------------------------------------------------------
709 * Remove all file names to the internal list of images to read.
711 void vtkGdcmReader::RemoveAllInternalFileName(void)
713 this->InternalFileNameList.clear();
717 * Adds a file name to the internal list of images to read.
719 void vtkGdcmReader::AddInternalFileName(const char *name)
721 char *LocalName = new char[strlen(name) + 1];
722 strcpy(LocalName, name);
723 this->InternalFileNameList.push_back(LocalName);
728 * Loads the contents of the image/volume contained by gdcm::File* f at
729 * the Dest memory address. Returns the size of the data loaded.
731 size_t vtkGdcmReader::LoadImageInMemory(
734 const unsigned long updateProgressTarget,
735 unsigned long &updateProgressCount)
737 // vtkDebugMacro(<< "Copying to memory image [" << f->GetFileName() << "]");
739 return DoTheLoadingJob (f,
741 updateProgressTarget,
742 updateProgressCount);
746 * Loads the contents of the image/volume contained by char *fileName at
747 * the dest memory address. Returns the size of the data loaded.
749 size_t vtkGdcmReader::LoadImageInMemory(
750 std::string fileName,
752 const unsigned long updateProgressTarget,
753 unsigned long &updateProgressCount)
755 vtkDebugMacro(<< "Copying to memory image [" << fileName.c_str() << "]");
758 f = new gdcm::File();
759 f->SetLoadMode( LoadMode );
760 f->SetFileName( fileName.c_str() );
763 return DoTheLoadingJob (f,
765 updateProgressTarget,
766 updateProgressCount);
771 * Service method for LoadImageInMemory
773 size_t vtkGdcmReader::DoTheLoadingJob (gdcm::File *f,
775 const unsigned long updateProgressTarget,
776 unsigned long &updateProgressCount)
778 gdcm::FileHelper *fileH = new gdcm::FileHelper( f );
779 fileH->SetUserFunction( UserFunction );
783 // If the data structure of vtk for image/volume representation
784 // were straigthforwards the following would be enough:
785 // GdcmFile.GetImageDataIntoVector((void*)Dest, size);
786 // But vtk chooses to invert the lines of an image, that is the last
787 // line comes first (for some axis related reasons?). Hence we need
788 // to load the image line by line, starting from the end.
790 int numColumns = fileH->GetFile()->GetXSize();
791 int numLines = fileH->GetFile()->GetYSize();
792 int numPlanes = fileH->GetFile()->GetZSize();
793 int lineSize = NumComponents * numColumns * fileH->GetFile()->GetPixelSize();
794 int planeSize = lineSize * numLines;
798 if( fileH->GetFile()->HasLUT() && AllowLookupTable )
800 size = fileH->GetImageDataSize();
801 src = (unsigned char*) fileH->GetImageDataRaw();
802 unsigned char *lut = (unsigned char*) fileH->GetLutRGBA();
804 if(!this->LookupTable)
806 this->LookupTable = vtkLookupTable::New();
809 this->LookupTable->SetNumberOfTableValues(256);
810 for (int tmp=0; tmp<256; tmp++)
812 this->LookupTable->SetTableValue(tmp,
813 (float)lut[4*tmp+0]/255.0,
814 (float)lut[4*tmp+1]/255.0,
815 (float)lut[4*tmp+2]/255.0,
818 this->LookupTable->SetRange(0,255);
819 vtkDataSetAttributes *a = this->GetOutput()->GetPointData();
820 a->GetScalars()->SetLookupTable(this->LookupTable);
825 size = fileH->GetImageDataSize();
826 src = (unsigned char*)fileH->GetImageData();
829 unsigned char *dst = dest + planeSize - lineSize;
830 for (int plane = 0; plane < numPlanes; plane++)
832 for (int line = 0; line < numLines; line++)
834 // Copy one line at proper destination:
835 memcpy((void*)dst, (void*)src, lineSize);
838 // Update progress related:
839 if (!(updateProgressCount%updateProgressTarget))
841 this->UpdateProgress(updateProgressCount/(50.0*updateProgressTarget));
843 updateProgressCount++;
845 dst += 2 * planeSize;
851 // -------------------------------------------------------------------------
853 // We assume the use *does* know all the files whose names
854 // are in InternalFileNameList exist, may be open, are gdcm-readable
855 // have the same sizes, have the same 'pixel' type, are single frame
856 // have the same color convention, ..., anything else ?
858 int vtkGdcmReader::CheckFileCoherenceLight()
860 std::list<std::string>::iterator filename = InternalFileNameList.begin();
863 GdcmFile.SetLoadMode( LoadMode );
864 GdcmFile.SetFileName(filename->c_str() );
867 if (!GdcmFile.IsReadable())
869 vtkErrorMacro(<< "Gdcm cannot parse file " << filename->c_str());
870 vtkErrorMacro(<< "you should try vtkGdcmReader::CheckFileCoherence "
871 << "instead of vtkGdcmReader::CheckFileCoherenceLight");
874 int NX = GdcmFile.GetXSize();
875 int NY = GdcmFile.GetYSize();
876 // CheckFileCoherenceLight should be called *only* when user knows
877 // he deals with single frames files.
878 // Z size is then the number of files.
879 int NZ = InternalFileNameList.size();
880 std::string type = GdcmFile.GetPixelType();
881 vtkDebugMacro(<< "The first file is taken as reference: "
882 << filename->c_str());
883 vtkDebugMacro(<< "Image dimensions of reference file as read from Gdcm:"
884 << NX << " " << NY << " " << NZ);
885 vtkDebugMacro(<< "Number of planes added to the stack: " << NZ);
886 // Set aside the size of the image
887 this->NumColumns = NX;
889 this->ImageType = type;
890 this->PixelSize = GdcmFile.GetPixelSize();
892 if( GdcmFile.HasLUT() && this->AllowLookupTable )
894 // I could raise an error is AllowLookupTable is on and HasLUT() off
895 this->NumComponents = GdcmFile.GetNumberOfScalarComponentsRaw();
899 this->NumComponents = GdcmFile.GetNumberOfScalarComponents(); //rgb or mono
903 this->DataSpacing[0] = GdcmFile.GetXSpacing();
904 this->DataSpacing[1] = GdcmFile.GetYSpacing();
905 this->DataSpacing[2] = GdcmFile.GetZSpacing();
907 return InternalFileNameList.size();
910 // We assume the use *does* know all the files whose names
911 // are in InternalFileNameList exist, may be open, are gdcm-readable
912 // have the same sizes, have the same 'pixel' type, are single frame
913 // have the same color convention, ..., anything else ?
915 int vtkGdcmReader::CheckFileCoherenceAlreadyDone()
917 if ( CoherentFileList->empty() )
919 vtkErrorMacro(<< "Coherent File List is empty ");
923 gdcm::File *gdcmFile = (*CoherentFileList)[0];
925 int NX = gdcmFile->GetXSize();
926 int NY = gdcmFile->GetYSize();
927 // CheckFileCoherenceLight should be called *only* when user knows
928 // he deals with single frames files.
929 // Z size is then the number of files.
930 // --> TODO : loop on the File* to get NZ of each one !
931 int NZ = CoherentFileList->size();
932 std::string type = gdcmFile->GetPixelType();
933 //vtkDebugMacro(<< "The first file is taken as reference: "
934 // << (*CoherentFileList)[0]->GetFileName() );
935 vtkDebugMacro(<< "Image dimensions of reference file as read from Gdcm:"
936 << NX << " " << NY << " " << NZ);
937 vtkDebugMacro(<< "Number of planes added to the stack: " << NZ);
938 // Set aside the size of the image
939 this->NumColumns = NX;
941 this->ImageType = type;
942 this->PixelSize = gdcmFile->GetPixelSize();
944 if( gdcmFile->HasLUT() && this->AllowLookupTable )
946 // I could raise an error is AllowLookupTable is on and HasLUT() off
947 this->NumComponents = gdcmFile->GetNumberOfScalarComponentsRaw();
951 this->NumComponents = gdcmFile->GetNumberOfScalarComponents(); //rgb or mono
955 this->DataSpacing[0] = gdcmFile->GetXSpacing();
956 this->DataSpacing[1] = gdcmFile->GetYSpacing();
957 this->DataSpacing[2] = gdcmFile->GetZSpacing();
961 //-----------------------------------------------------------------------------