/usr/include/InsightToolkit/IO/itkImageFileReader.txx is in libinsighttoolkit3-dev 3.20.1+git20120521-5.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 | /*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkImageFileReader.txx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef __itkImageFileReader_txx
#define __itkImageFileReader_txx
#include "itkImageFileReader.h"
#include "itkObjectFactory.h"
#include "itkImageIOFactory.h"
#include "itkConvertPixelBuffer.h"
#include "itkImageRegion.h"
#include "itkPixelTraits.h"
#include "itkVectorImage.h"
#include <itksys/SystemTools.hxx>
#include <fstream>
namespace itk
{
template <class TOutputImage, class ConvertPixelTraits>
ImageFileReader<TOutputImage, ConvertPixelTraits>
::ImageFileReader()
{
m_ImageIO = 0;
m_FileName = "";
m_UserSpecifiedImageIO = false;
m_UseStreaming = true;
}
template <class TOutputImage, class ConvertPixelTraits>
ImageFileReader<TOutputImage, ConvertPixelTraits>
::~ImageFileReader()
{
}
template <class TOutputImage, class ConvertPixelTraits>
void ImageFileReader<TOutputImage, ConvertPixelTraits>
::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
if (m_ImageIO)
{
os << indent << "ImageIO: \n";
m_ImageIO->Print(os, indent.GetNextIndent());
}
else
{
os << indent << "ImageIO: (null)" << "\n";
}
os << indent << "UserSpecifiedImageIO flag: " << m_UserSpecifiedImageIO << "\n";
os << indent << "m_FileName: " << m_FileName << "\n";
os << indent << "m_UseStreaming: " << m_UseStreaming << "\n";
}
template <class TOutputImage, class ConvertPixelTraits>
void
ImageFileReader<TOutputImage, ConvertPixelTraits>
::SetImageIO( ImageIOBase * imageIO)
{
itkDebugMacro("setting ImageIO to " << imageIO );
if (this->m_ImageIO != imageIO )
{
this->m_ImageIO = imageIO;
this->Modified();
}
m_UserSpecifiedImageIO = true;
}
template <class TOutputImage, class ConvertPixelTraits>
void
ImageFileReader<TOutputImage, ConvertPixelTraits>
::GenerateOutputInformation(void)
{
typename TOutputImage::Pointer output = this->GetOutput();
itkDebugMacro(<<"Reading file for GenerateOutputInformation()" << m_FileName);
// Check to see if we can read the file given the name or prefix
//
if ( m_FileName == "" )
{
throw ImageFileReaderException(__FILE__, __LINE__, "FileName must be specified", ITK_LOCATION);
}
// Test if the file exists and if it can be opened.
// An exception will be thrown otherwise.
// We catch the exception because some ImageIO's may not actually
// open a file. Still reports file error if no ImageIO is loaded.
try
{
m_ExceptionMessage = "";
this->TestFileExistanceAndReadability();
}
catch(itk::ExceptionObject &err)
{
m_ExceptionMessage = err.GetDescription();
}
if ( m_UserSpecifiedImageIO == false ) //try creating via factory
{
m_ImageIO = ImageIOFactory::CreateImageIO( m_FileName.c_str(), ImageIOFactory::ReadMode );
}
if ( m_ImageIO.IsNull() )
{
OStringStream msg;
msg << " Could not create IO object for file "
<< m_FileName.c_str() << std::endl;
if (m_ExceptionMessage.size())
{
msg << m_ExceptionMessage;
}
else
{
msg << " Tried to create one of the following:" << std::endl;
std::list<LightObject::Pointer> allobjects =
ObjectFactoryBase::CreateAllInstance("itkImageIOBase");
for(std::list<LightObject::Pointer>::iterator i = allobjects.begin();
i != allobjects.end(); ++i)
{
ImageIOBase* io = dynamic_cast<ImageIOBase*>(i->GetPointer());
msg << " " << io->GetNameOfClass() << std::endl;
}
msg << " You probably failed to set a file suffix, or" << std::endl;
msg << " set the suffix to an unsupported type." << std::endl;
}
ImageFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION);
throw e;
return;
}
// Got to allocate space for the image. Determine the characteristics of
// the image.
//
m_ImageIO->SetFileName(m_FileName.c_str());
m_ImageIO->ReadImageInformation();
SizeType dimSize;
double spacing[ TOutputImage::ImageDimension ];
double origin[ TOutputImage::ImageDimension ];
typename TOutputImage::DirectionType direction;
std::vector<std::vector<double> > directionIO;
const unsigned int numberOfDimensionsIO = m_ImageIO->GetNumberOfDimensions();
if( numberOfDimensionsIO > TOutputImage::ImageDimension )
{
for( unsigned int k = 0; k < numberOfDimensionsIO; k++ )
{
directionIO.push_back( m_ImageIO->GetDefaultDirection(k) );
}
}
else
{
for( unsigned int k = 0; k < numberOfDimensionsIO; k++ )
{
directionIO.push_back( m_ImageIO->GetDirection(k) );
}
}
std::vector<double> axis;
for(unsigned int i=0; i<TOutputImage::ImageDimension; i++)
{
if( i < numberOfDimensionsIO )
{
dimSize[i] = m_ImageIO->GetDimensions(i);
spacing[i] = m_ImageIO->GetSpacing(i);
origin[i] = m_ImageIO->GetOrigin(i);
// Please note: direction cosines are stored as columns of the
// direction matrix
axis = directionIO[i];
for( unsigned j=0; j<TOutputImage::ImageDimension; j++ )
{
if (j < numberOfDimensionsIO )
{
direction[j][i] = axis[j];
}
else
{
direction[j][i] = 0.0;
}
}
}
else
{
// Number of dimensions in the output is more than number of dimensions
// in the ImageIO object (the file). Use default values for the size,
// spacing, origin and direction for the final (degenerate) dimensions.
dimSize[i] = 1;
spacing[i] = 1.0;
origin[i] = 0.0;
for (unsigned j = 0; j < TOutputImage::ImageDimension; j++)
{
if (i == j)
{
direction[j][i] = 1.0;
}
else
{
direction[j][i] = 0.0;
}
}
}
}
output->SetSpacing( spacing ); // Set the image spacing
output->SetOrigin( origin ); // Set the image origin
output->SetDirection( direction ); // Set the image direction cosines
//Copy MetaDataDictionary from instantiated reader to output image.
output->SetMetaDataDictionary(m_ImageIO->GetMetaDataDictionary());
this->SetMetaDataDictionary(m_ImageIO->GetMetaDataDictionary());
IndexType start;
start.Fill(0);
ImageRegionType region;
region.SetSize(dimSize);
region.SetIndex(start);
// If a VectorImage, this requires us to set the
// VectorLength before allocate
if( strcmp( output->GetNameOfClass(), "VectorImage" ) == 0 )
{
typedef typename TOutputImage::AccessorFunctorType AccessorFunctorType;
AccessorFunctorType::SetVectorLength( output, m_ImageIO->GetNumberOfComponents() );
}
output->SetLargestPossibleRegion(region);
}
template <class TOutputImage, class ConvertPixelTraits>
void
ImageFileReader<TOutputImage, ConvertPixelTraits>
::TestFileExistanceAndReadability()
{
// Test if the file exists.
if( ! itksys::SystemTools::FileExists( m_FileName.c_str() ) )
{
ImageFileReaderException e(__FILE__, __LINE__);
OStringStream msg;
msg <<"The file doesn't exist. "
<< std::endl << "Filename = " << m_FileName
<< std::endl;
e.SetDescription(msg.str().c_str());
throw e;
return;
}
// Test if the file can be open for reading access.
std::ifstream readTester;
readTester.open( m_FileName.c_str() );
if( readTester.fail() )
{
readTester.close();
OStringStream msg;
msg <<"The file couldn't be opened for reading. "
<< std::endl << "Filename: " << m_FileName
<< std::endl;
ImageFileReaderException e(__FILE__, __LINE__,msg.str().c_str(),ITK_LOCATION);
throw e;
return;
}
readTester.close();
}
template <class TOutputImage, class ConvertPixelTraits>
void
ImageFileReader<TOutputImage, ConvertPixelTraits>
::EnlargeOutputRequestedRegion(DataObject *output)
{
itkDebugMacro (<< "Starting EnlargeOutputRequestedRegion() ");
typename TOutputImage::Pointer out = dynamic_cast<TOutputImage*>(output);
typename TOutputImage::RegionType largestRegion = out->GetLargestPossibleRegion();
ImageRegionType streamableRegion;
// The following code converts the ImageRegion (templated over dimension)
// into an ImageIORegion (not templated over dimension).
ImageRegionType imageRequestedRegion = out->GetRequestedRegion();
ImageIORegion ioRequestedRegion( TOutputImage::ImageDimension );
typedef ImageIORegionAdaptor< TOutputImage::ImageDimension > ImageIOAdaptor;
ImageIOAdaptor::Convert( imageRequestedRegion, ioRequestedRegion, largestRegion.GetIndex() );
// Tell the IO if we should use streaming while reading
m_ImageIO->SetUseStreamedReading(m_UseStreaming);
// Delegate to the ImageIO the computation of how the
// requested region must be enlarged.
m_ActualIORegion =
m_ImageIO->GenerateStreamableReadRegionFromRequestedRegion( ioRequestedRegion );
// the m_ActualIORegion may be more dimensions then the output
// Image, in which case we still need to read this larger region to
// support reading the "first slice" of a larger image
// see bug 9212
// convert the IORegion to a ImageRegion (which is dimension templated)
// if the ImageIO must read a higher dimension region, this will
// truncate the last dimensions
ImageIOAdaptor::Convert( m_ActualIORegion, streamableRegion, largestRegion.GetIndex() );
// Check whether the imageRequestedRegion is fully contained inside the
// streamable region. Since, ImageRegion::IsInside regards zero
// sized regions, as not being inside any other region, we must
// specially check this condition to enable zero sized regions to
// pass the region propagation phase of the pipeline.
if( !streamableRegion.IsInside( imageRequestedRegion )
&& imageRequestedRegion.GetNumberOfPixels() != 0)
{
// we must use a InvalidRequestedRegionError since
// DataObject::PropagateRequestedRegion() has an exception
// specification
::itk::OStringStream message;
message << "ImageIO returns IO region that does not fully contain the requested region"
<< "Requested region: " << imageRequestedRegion
<< "StreamableRegion region: " << streamableRegion;
InvalidRequestedRegionError e(__FILE__, __LINE__);
e.SetLocation(ITK_LOCATION);
e.SetDescription(message.str().c_str());
throw e;
}
itkDebugMacro (<< "RequestedRegion is set to:" << streamableRegion << " while the m_ActualIORegion is: " << m_ActualIORegion);
out->SetRequestedRegion( streamableRegion );
}
template <class TOutputImage, class ConvertPixelTraits>
void ImageFileReader<TOutputImage, ConvertPixelTraits>
::GenerateData()
{
typename TOutputImage::Pointer output = this->GetOutput();
itkDebugMacro ( << "ImageFileReader::GenerateData() \n"
<< "Allocating the buffer with the EnlargedRequestedRegion \n"
<< output->GetRequestedRegion() << "\n");
// Test if the file exists and if it can be opened.
// An exception will be thrown otherwise, since we can't
// successfully read the file. We catch the exception because some
// ImageIO's may not actually open a file. Still
// reports file error if no ImageIO is loaded.
try
{
m_ExceptionMessage = "";
this->TestFileExistanceAndReadability();
}
catch(itk::ExceptionObject &err)
{
m_ExceptionMessage = err.GetDescription();
}
// Tell the ImageIO to read the file
m_ImageIO->SetFileName(m_FileName.c_str());
itkDebugMacro (<< "Setting imageIO IORegion to: " << m_ActualIORegion );
m_ImageIO->SetIORegion( m_ActualIORegion );
char *loadBuffer = 0;
// the size of the buffer is computed based on the actual number of
// pixels to be read and the actual size of the pixels to be read
// (as opposed to the sizes of the output)
size_t sizeOfActualIORegion = m_ActualIORegion.GetNumberOfPixels() * (m_ImageIO->GetComponentSize()*m_ImageIO->GetNumberOfComponents());
bool freeLoadBuffer = true;
try
{
if ( (m_ImageIO->GetComponentTypeInfo()
!= typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType) )
|| (m_ImageIO->GetNumberOfComponents()
!= ConvertPixelTraits::GetNumberOfComponents() ))
{
// the pixel types don't match so a type conversion needs to be
// performed
itkDebugMacro(<< "Buffer conversion required from: "
<< m_ImageIO->GetComponentTypeInfo().name()
<< " to: "
<< typeid(ITK_TYPENAME ConvertPixelTraits::ComponentType).name());
this->AllocateOutputs();
// To use OwnBuffer, that feature must be supported by the reader
// and the number of pixels in that buffer must equal the number
// of pixels expected as output. Otherwise the Read() function
// must be called.
if( ! m_ImageIO->CanUseOwnBuffer()
|| m_ActualIORegion.GetNumberOfPixels()
!= output->GetBufferedRegion().GetNumberOfPixels() )
{
loadBuffer = new char[ sizeOfActualIORegion ];
m_ImageIO->Read( static_cast< void *>(loadBuffer) );
freeLoadBuffer = true;
}
else
{
m_ImageIO->ReadUsingOwnBuffer();
loadBuffer = static_cast< char * >( m_ImageIO->GetOwnBuffer() );
freeLoadBuffer = false;
}
// See note below as to why the buffered region is needed and
// not actualIOregion
this->DoConvertBuffer(static_cast< void *>(loadBuffer),
output->GetBufferedRegion().GetNumberOfPixels() );
}
else if ( m_ActualIORegion.GetNumberOfPixels()
!= output->GetBufferedRegion().GetNumberOfPixels() )
{
// NOTE:
// for the number of pixels read and the number of pixels
// requested do not match, the dimensions of the two regions may
// be different, therefore we buffer and copy the pixels
itkDebugMacro(<< "Buffer required because file dimension is greater then image dimension");
this->AllocateOutputs();
OutputImagePixelType *outputBuffer =
output->GetPixelContainer()->GetBufferPointer();
loadBuffer = new char[ sizeOfActualIORegion ];
m_ImageIO->Read( static_cast< void *>(loadBuffer) );
freeLoadBuffer = true;
// we use std::copy here as it should be optimized to memcpy for
// plain old data, but still is oop
std::copy( reinterpret_cast<const OutputImagePixelType *>(loadBuffer),
reinterpret_cast<const OutputImagePixelType *>(loadBuffer)
+ output->GetBufferedRegion().GetNumberOfPixels(),
outputBuffer );
}
else
{
itkDebugMacro(<< "No buffer conversion required.");
// We know the number of pixels read and the type of pixels read
// matches the expected output, so use OwnBuffer if supported
// by the reader.
if( ! m_ImageIO->CanUseOwnBuffer() )
{
this->AllocateOutputs();
OutputImagePixelType *outputBuffer =
output->GetPixelContainer()->GetBufferPointer();
m_ImageIO->Read( outputBuffer );
freeLoadBuffer = false;
}
else
{
m_ImageIO->ReadUsingOwnBuffer();
output->GetPixelContainer()->SetImportPointer(
reinterpret_cast< OutputImagePixelType * >(
m_ImageIO->GetOwnBuffer() ), sizeOfActualIORegion, false );
freeLoadBuffer = false;
}
}
}
catch (...)
{
// if an exception is thrown catch it
if( freeLoadBuffer && loadBuffer )
{
// clean up
delete [] loadBuffer;
loadBuffer = 0;
}
// then rethrow
throw;
}
// clean up
if( freeLoadBuffer && loadBuffer )
{
delete [] loadBuffer;
loadBuffer = 0;
}
}
template <class TOutputImage, class ConvertPixelTraits>
void
ImageFileReader<TOutputImage, ConvertPixelTraits>
::DoConvertBuffer(void* inputData,
size_t numberOfPixels)
{
// get the pointer to the destination buffer
OutputImagePixelType *outputData =
this->GetOutput()->GetPixelContainer()->GetBufferPointer();
// TODO:
// Pass down the PixelType (RGB, VECTOR, etc.) so that any vector to
// scalar conversion be type specific. i.e. RGB to scalar would use
// a formula to convert to luminance, VECTOR to scalar would use
// vector magnitude.
// Create a macro as this code is a bit lengthy and repetitive
// if the ImageIO pixel type is typeid(type) then use the ConvertPixelBuffer
// class to convert the data block to TOutputImage's pixel type
// see DefaultConvertPixelTraits and ConvertPixelBuffer
// The first else if block applies only to images of type itk::VectorImage
// VectorImage needs to copy out the buffer differently.. The buffer is of
// type InternalPixelType, but each pixel is really 'k' consecutive pixels.
#define ITK_CONVERT_BUFFER_IF_BLOCK(type) \
else if( m_ImageIO->GetComponentTypeInfo() == typeid(type) ) \
{ \
if( strcmp( this->GetOutput()->GetNameOfClass(), "VectorImage" ) == 0 ) \
{ \
ConvertPixelBuffer< \
type, \
OutputImagePixelType, \
ConvertPixelTraits \
> \
::ConvertVectorImage( \
static_cast<type*>(inputData), \
m_ImageIO->GetNumberOfComponents(), \
outputData, \
numberOfPixels); \
} \
else \
{ \
ConvertPixelBuffer< \
type, \
OutputImagePixelType, \
ConvertPixelTraits \
> \
::Convert( \
static_cast<type*>(inputData), \
m_ImageIO->GetNumberOfComponents(), \
outputData, \
numberOfPixels); \
} \
}
if(0)
{
}
ITK_CONVERT_BUFFER_IF_BLOCK(unsigned char)
ITK_CONVERT_BUFFER_IF_BLOCK(char)
ITK_CONVERT_BUFFER_IF_BLOCK(unsigned short)
ITK_CONVERT_BUFFER_IF_BLOCK( short)
ITK_CONVERT_BUFFER_IF_BLOCK(unsigned int)
ITK_CONVERT_BUFFER_IF_BLOCK( int)
ITK_CONVERT_BUFFER_IF_BLOCK(unsigned long)
ITK_CONVERT_BUFFER_IF_BLOCK( long)
ITK_CONVERT_BUFFER_IF_BLOCK(float)
ITK_CONVERT_BUFFER_IF_BLOCK( double)
else
{
ImageFileReaderException e(__FILE__, __LINE__);
OStringStream msg;
msg <<"Couldn't convert component type: "
<< std::endl << " "
<< m_ImageIO->GetComponentTypeAsString(m_ImageIO->GetComponentType())
<< std::endl << "to one of: "
<< std::endl << " " << typeid(unsigned char).name()
<< std::endl << " " << typeid(char).name()
<< std::endl << " " << typeid(unsigned short).name()
<< std::endl << " " << typeid(short).name()
<< std::endl << " " << typeid(unsigned int).name()
<< std::endl << " " << typeid(int).name()
<< std::endl << " " << typeid(unsigned long).name()
<< std::endl << " " << typeid(long).name()
<< std::endl << " " << typeid(float).name()
<< std::endl << " " << typeid(double).name()
<< std::endl;
e.SetDescription(msg.str().c_str());
e.SetLocation(ITK_LOCATION);
throw e;
return;
}
#undef ITK_CONVERT_BUFFER_IF_BLOCK
}
} //namespace ITK
#endif
|