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 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
|
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkMRCImageIO.cxx
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.
=========================================================================*/
#include "itkMRCImageIO.h"
#include "itkByteSwapper.h"
#include "itkIntTypes.h"
#include "itkMetaDataObject.h"
#include "itkIOCommon.h"
#include "itkGenericUtilities.h"
#include <numeric>
#include <algorithm>
#include <fstream>
#include <itksys/SystemTools.hxx>
namespace itk
{
const char *MRCImageIO::m_MetaDataHeaderName = "MRCHeader";
MRCImageIO::MRCImageIO()
: StreamingImageIOBase()
{
this->SetNumberOfComponents(1);
this->SetNumberOfDimensions(3);
this->SetFileTypeToBinary();
this->AddSupportedReadExtension(".mrc");
this->AddSupportedReadExtension(".rec");
this->AddSupportedWriteExtension(".mrc");
this->AddSupportedWriteExtension(".rec");
}
void MRCImageIO::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
}
bool MRCImageIO::CanReadFile(const char* filename)
{
std::string fname = filename;
if ( fname != "" &&
( fname.find(".mrc") < fname.length() ||
fname.find(".rec") < fname.length() ) )
{
return true;
}
std::ifstream file;
try
{
// this may throw an expection, but we just return false
this->OpenFileForReading(file, filename);
}
catch (...)
{
return false;
}
itkDebugMacro( << "Reading Magic numbers " << filename );
char map[4];
char stamp[4];
// special offset to magic number
file.seekg(208);
if( !this->ReadBufferAsBinary( file, static_cast<void*>(&map), 4 ) ||
!this->ReadBufferAsBinary( file, static_cast<void*>(&stamp), 4 ))
{
return false;
}
// check the magic number
if ( strncmp(map, magicMAP, 4) != 0 )
{
return false;
}
return true;
}
MRCImageIO::SizeType MRCImageIO::GetHeaderSize( void ) const
{
if ( m_MRCHeader.IsNull() )
{
itkExceptionMacro(<< "Must read info first");
}
return m_MRCHeader->GetExtendedHeaderSize() + m_MRCHeader->GetHeaderSize();
}
void MRCImageIO::ReadImageInformation( void ) {
std::ifstream file;
this->InternalReadImageInformation( file );
if ( m_MRCHeader->IsOriginalHeaderBigEndian() )
{
this->SetByteOrderToBigEndian();
}
else
{
this->SetByteOrderToLittleEndian();
}
const MRCHeaderObject::Header & header = m_MRCHeader->GetHeader();
// fixed types defined by header
switch ( header.mode )
{
case MRCHeaderObject::MRCHEADER_MODE_UINT8:
{
// todo: the format is unclear weather this is signed or
// unsigned, it would be best to check the min and max in the
// header to see what makes since
this->SetComponentType( UCHAR );
this->SetNumberOfComponents( 1 );
this->SetPixelType( SCALAR );
break;
}
case MRCHeaderObject::MRCHEADER_MODE_IN16:
{
this->SetComponentType( SHORT );
this->SetNumberOfComponents( 1 );
this->SetPixelType( SCALAR );
break;
}
case MRCHeaderObject::MRCHEADER_MODE_FLOAT:
{
this->SetComponentType( FLOAT );
this->SetNumberOfComponents( 1 );
this->SetPixelType( SCALAR );
break;
}
case MRCHeaderObject::MRCHEADER_MODE_COMPLEX_INT16:
{
// ITK does not support short complex well
// but if the program has gotten this far we can just write it out
this->SetComponentType( SHORT );
this->SetNumberOfComponents( 2 );
this->SetPixelType( COMPLEX );
break;
}
case MRCHeaderObject::MRCHEADER_MODE_COMPLEX_FLOAT:
{
this->SetComponentType( FLOAT );
this->SetNumberOfComponents( 2 );
this->SetPixelType( COMPLEX );
break;
}
case MRCHeaderObject::MRCHEADER_MODE_UINT16:
{
this->SetComponentType( USHORT );
this->SetNumberOfComponents( 1 );
this->SetPixelType( SCALAR );
break;
}
case MRCHeaderObject::MRCHEADER_MODE_RGB_BYTE:
{
this->SetComponentType( UCHAR );
this->SetNumberOfComponents( 3 );
this->SetPixelType( RGB );
break;
}
default:
{
itkExceptionMacro(<< "Unrecognized mode");
}
}
if ( header.xlen == 0 &&
header.ylen == 0 &&
header.zlen == 0 )
{
// if the spacing was not set in the header then this is the
// default
m_Spacing[0] = 1.0;
m_Spacing[1] = 1.0;
m_Spacing[2] = 1.0;
}
else
{
m_Spacing[0] = header.xlen / float(header.mx);
m_Spacing[1] = header.ylen / float(header.my);
m_Spacing[2] = header.zlen / float(header.mz);
}
// copy the origin
m_Origin[0] = header.xorg;
m_Origin[1] = header.yorg;
m_Origin[2] = header.zorg;
// copy the size of the dimensions
m_Dimensions[0] = header.nx;
m_Dimensions[1] = header.ny;
m_Dimensions[2] = header.nz;
// add the MRCHeader object into the metadata dictionary to that it
// can be accessed
MetaDataDictionary &thisDic=this->GetMetaDataDictionary();
std::string classname( this->GetNameOfClass() );
EncapsulateMetaData<std::string>( thisDic, ITK_InputFilterName, classname );
EncapsulateMetaData<MRCHeaderObject::ConstPointer>( thisDic, m_MetaDataHeaderName, MRCHeaderObject::ConstPointer(m_MRCHeader) );
return;
}
// methods to load the data into the MRCHeader member variable
void MRCImageIO::InternalReadImageInformation(std::ifstream &file) {
char *buffer = 0;
try
{
m_MRCHeader = MRCHeaderObject::New();
itkDebugMacro(<< "Reading Information ");
this->OpenFileForReading(file, this->m_FileName.c_str());
buffer = new char[m_MRCHeader->GetHeaderSize()];
if( !this->ReadBufferAsBinary( file, static_cast<void*>(buffer), m_MRCHeader->GetHeaderSize()) )
{
itkExceptionMacro(<<"Header Read failed: Wanted "
<< m_MRCHeader->GetHeaderSize()
<< " bytes, but read "
<< file.gcount() << " bytes.");
}
// convert the raw buffer into the header
if ( !m_MRCHeader->SetHeader(reinterpret_cast<const MRCHeaderObject::Header*>(buffer) ) )
{
itkExceptionMacro(<< "Unrecognized header");
}
delete [] buffer;
buffer = 0;
buffer = new char[m_MRCHeader->GetExtendedHeaderSize()];
if( !this->ReadBufferAsBinary( file, static_cast<void*>(buffer), m_MRCHeader->GetExtendedHeaderSize()) )
{
itkExceptionMacro(<<"Extended Header Read failed.");
}
m_MRCHeader->SetExtendedHeader(buffer);
}
catch (...)
{
// clean up dynamic allocation
if (buffer)
delete [] buffer;
buffer = 0;
throw;
}
delete [] buffer;
}
void MRCImageIO
::Read(void *buffer)
{
std::ifstream file;
if( this->RequestedToStream( ) )
{
// open and stream read
this->OpenFileForReading(file, this->m_FileName.c_str());
this->StreamReadBufferAsBinary(file, buffer);
}
else
{
// open the file
this->OpenFileForReading(file, this->m_FileName.c_str());
// seek base the header
std::streampos dataPos = static_cast<std::streampos>( this->GetHeaderSize() );
file.seekg( dataPos, std::ios::beg );
if ( file.fail() )
{
itkExceptionMacro(<<"Failed seeking to data position");
}
// read the image
this->ReadBufferAsBinary( file, buffer, this->GetImageSizeInBytes() );
}
int size = this->GetComponentSize();
switch( size )
{
case 1:
break;
case 2:
this->GetByteOrder() == BigEndian ?
ByteSwapper<uint16_t>::SwapRangeFromSystemToBigEndian((uint16_t *)buffer, this->GetImageSizeInComponents() ) :
ByteSwapper<uint16_t>::SwapRangeFromSystemToLittleEndian((uint16_t *)buffer, this->GetImageSizeInComponents() );
break;
case 4:
this->GetByteOrder() == BigEndian ?
ByteSwapper<uint32_t>::SwapRangeFromSystemToBigEndian((uint32_t *)buffer, this->GetImageSizeInComponents() ) :
ByteSwapper<uint32_t>::SwapRangeFromSystemToLittleEndian((uint32_t *)buffer, this->GetImageSizeInComponents() );
break;
default:
itkExceptionMacro(<< "Unknown component size");
}
}
bool MRCImageIO::CanWriteFile(const char* fname)
{
std::string filename = fname;
if ( filename.length() > 4 &&
(filename.find(".mrc") == filename.length() - 4 ||
filename.find(".rec") == filename.length() - 4 ) )
{
return true;
}
return false;
}
void MRCImageIO::UpdateHeaderFromImageIO( void )
{
MRCHeaderObject::Header header;
memset(&header, 0, sizeof(MRCHeaderObject::Header));
itkAssertOrThrowMacro ( this->GetNumberOfDimensions() != 0, "Invalid Dimension for Writting" );
if ( this->GetNumberOfDimensions() > 3 )
{
itkExceptionMacro(<<"MRC Writer can not write more than 3-dimensional images");
}
// magic number
strncpy(header.cmap, magicMAP, 4);
if ( ByteSwapper<void*>::SystemIsBigEndian() )
header.stamp[0] = 17;
else
header.stamp[0] = 68;
header.alpha = 90;
header.beta = 90;
header.gamma = 90;
header.mapc = MRCHeaderObject::MRCHEADER_MAP_X;
header.mapr = MRCHeaderObject::MRCHEADER_MAP_Y;
header.maps = MRCHeaderObject::MRCHEADER_MAP_Z;
header.mx = header.nx = m_Dimensions[0];
header.my = header.ny = ( this->GetNumberOfDimensions() >= 2 ) ? m_Dimensions[1] : 1;
header.mz = header.nz = ( this->GetNumberOfDimensions() >= 3 ) ? m_Dimensions[2] : 1;
header.mode = -1;
if (this->GetPixelType() == SCALAR)
{
if (this->GetComponentType() == UCHAR)
{
header.mode = MRCHeaderObject::MRCHEADER_MODE_UINT8;
}
else if (this->GetComponentType() == SHORT)
{
header.mode = MRCHeaderObject::MRCHEADER_MODE_IN16;
}
else if (this->GetComponentType() == FLOAT)
{
header.mode = MRCHeaderObject::MRCHEADER_MODE_FLOAT;
}
else if (this->GetComponentType() == USHORT)
{
header.mode = MRCHeaderObject::MRCHEADER_MODE_UINT16;
}
}
else if (this->GetPixelType() == COMPLEX)
{
// ITK does not support short complex well
// but if we have gotten this far, it's done
if (this->GetComponentType() == SHORT)
{
header.mode = MRCHeaderObject::MRCHEADER_MODE_COMPLEX_INT16;
}
else
if (this->GetComponentType() == FLOAT)
{
header.mode = MRCHeaderObject::MRCHEADER_MODE_COMPLEX_FLOAT;
}
}
else if (this->GetPixelType() == RGB
&& this->GetComponentType() == UCHAR)
{
header.mode = MRCHeaderObject::MRCHEADER_MODE_RGB_BYTE;
}
if (header.mode == -1)
{
itkExceptionMacro(<< "Unsupported pixel type: " << this->GetPixelTypeAsString( this->GetPixelType())
<< " " << this->GetComponentTypeAsString(this->GetComponentType())
<< std::endl
<< "Supported pixel types include unsigned byte, unsigned short, signed short, float, rgb unsigned char, float complex"
);
}
header.nxstart = 0;
header.nystart = 0;
header.nzstart = 0;
header.xlen = m_Spacing[0]*float(header.mx);
header.ylen = ( this->GetNumberOfDimensions() >= 2 ) ? m_Spacing[1]*float(header.my) : 1;
header.zlen = ( this->GetNumberOfDimensions() >= 3 ) ? m_Spacing[2]*float(header.mz) : 1;
header.xorg = m_Origin[0];
header.yorg = ( this->GetNumberOfDimensions() >= 2 ) ? m_Origin[1] : 0;
header.zorg = ( this->GetNumberOfDimensions() >= 3 ) ? m_Origin[2] : 0;
// the SetHeader method is used to set the all the internal variable
// of the header object correctly, and the data is verified
m_MRCHeader = MRCHeaderObject::New();
if (!m_MRCHeader->SetHeader(&header))
{
itkExceptionMacro(<< "Unexpected error setting header");
}
}
void MRCImageIO::WriteImageInformation( const void * buffer )
{
this->UpdateHeaderFromImageIO();
this->UpdateHeaderWithMinMaxMean( buffer );
std::ofstream file;
this->OpenFileForWriting(file, this->m_FileName.c_str(), true);
// write the header
const MRCHeaderObject::Header & header = m_MRCHeader->GetHeader();
file.write(static_cast<const char*>((void*)&(header)), 1024);
}
void MRCImageIO
::UpdateHeaderWithMinMaxMean( const void * bufferBegin )
{
// fixed types defined by header
const MRCHeaderObject::Header & header = m_MRCHeader->GetHeader();
switch ( header.mode )
{
case 0:
{
// scalar unsigned char
this->UpdateHeaderWithMinMaxMean(static_cast<const unsigned char*>(bufferBegin));
break;
}
case 1:
{
// scalar short
this->UpdateHeaderWithMinMaxMean(static_cast<const short*>(bufferBegin));
break;
}
case 2:
{
// scalar float
this->UpdateHeaderWithMinMaxMean(static_cast<const float*>(bufferBegin));
break;
}
case 3:
{
// complex short
// What is the best way to map complex to float?
// just set resonable values
m_MRCHeader->m_Header.amin = -1.0f;
m_MRCHeader->m_Header.amax = 1.0f;
m_MRCHeader->m_Header.amean = 0.0f;
break;
}
case 4:
{
// complex float
// What is the best way to map complex to float?
// just set resonable values
m_MRCHeader->m_Header.amin = -1.0f;
m_MRCHeader->m_Header.amax = 1.0f;
m_MRCHeader->m_Header.amean = 0.0f;
break;
}
case 6:
{
// scalar unsigned short
this->UpdateHeaderWithMinMaxMean(static_cast<const unsigned short*>(bufferBegin));
break;
}
case 16:
{
// RGB of unsigned char
// just set resonable values
m_MRCHeader->m_Header.amin = 0.0f;
m_MRCHeader->m_Header.amax = 255.0f;
m_MRCHeader->m_Header.amean = 127.5f;
break;
}
default:
{
itkExceptionMacro(<< "Unrecognized mode");
}
}
}
void MRCImageIO
::Write(const void* buffer)
{
if( this->RequestedToStream() )
{
// we assume that GetActualNumberOfSplitsForWriting is called before
// this methods and it will remove the file if a new header needs to
// be written
if (!itksys::SystemTools::FileExists( m_FileName.c_str() ))
{
this->WriteImageInformation( buffer );
std::ofstream file;
// open and stream write
this->OpenFileForWriting(file, this->m_FileName.c_str(), false);
// write one byte at the end of the file to allocate (this is a
// nifty trick which should not write the entire size of the file
// just allocate it, if the system supports sparse files)
std::streampos seekPos = this->GetImageSizeInBytes() + this->GetHeaderSize() - 1;
file.seekp( seekPos, std::ios::cur );
file.write("\0", 1);
file.seekp( 0 );
}
else
{
if ( m_MRCHeader.IsNull() )
{
// need to determin the size of the header in the file by
// reading the header into m_MRCHeader
// we assume that GetActualNumberOfSplitsForWriting is called
// to verify that the header and file is compatible with the
// region to be written, but this call will still overwrite
// the internal m_MRCHeader variable
std::ifstream file;
this->InternalReadImageInformation( file );
}
// TODO:
// how are we suppose to update min, max mean? we could be
// overwriting data, and we don't know what's already there if
// we were pasting
}
std::ofstream file;
// open and stream write
this->OpenFileForWriting(file, this->m_FileName.c_str(), false);
this->StreamWriteBufferAsBinary(file, buffer);
}
else
{
// this will truncate file and write header
this->WriteImageInformation( buffer );
std::ofstream file;
// open the file
this->OpenFileForWriting(file, this->m_FileName.c_str(), false);
// seek pass the header
std::streampos dataPos = static_cast<std::streampos>( this->GetHeaderSize() );
file.seekp( dataPos, std::ios::beg );
if ( file.fail() )
{
itkExceptionMacro(<<"Failed seeking to data position");
}
// read the image
if (!this->WriteBufferAsBinary( file, buffer, this->GetImageSizeInBytes() ))
{
itkExceptionMacro(<< "Could not write file: " << m_FileName);
}
}
}
} // namespace itk
|