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