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
|
/*
//
// Copyright 1997-2009 Torsten Rohlfing
//
// Copyright 2004-2013 SRI International
//
// This file is part of the Computational Morphometry Toolkit.
//
// http://www.nitrc.org/projects/cmtk/
//
// The Computational Morphometry Toolkit is free software: you can
// redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// The Computational Morphometry Toolkit is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with the Computational Morphometry Toolkit. If not, see
// <http://www.gnu.org/licenses/>.
//
// $Revision: 5436 $
//
// $LastChangedDate: 2018-12-10 19:01:20 -0800 (Mon, 10 Dec 2018) $
//
// $LastChangedBy: torstenrohlfing $
//
*/
#include "cmtkVolumeIO.h"
#include <System/cmtkExitException.h>
#include <System/cmtkStrUtility.h>
#include <System/cmtkFileUtils.h>
#include <System/cmtkProgress.h>
#include <System/cmtkMountPoints.h>
#include <System/cmtkDebugOutput.h>
#include <IO/cmtkStudy.h>
#include <IO/cmtkClassStreamInput.h>
#include <IO/cmtkClassStreamOutput.h>
#include <IO/cmtkVolumeFromFile.h>
#include <Base/cmtkTypes.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_LIBGEN_H
# include <libgen.h>
#endif
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <string>
namespace
cmtk
{
/** \addtogroup IO */
//@{
/// Environment variable that turns off writing output images in the array order of the input images.
const char* const CMTK_LEGACY_WRITE_IMAGES_RAS = "CMTK_LEGACY_WRITE_IMAGES_RAS";
/// Static global flag: when true, files are written compressed whenever possible.
bool VolumeIO::WriteCompressedOn = true;
UniformVolume::SmartPtr
VolumeIO::Read( const std::string& path )
{
UniformVolume::SmartPtr volume( NULL );
const std::string translatedPath = MountPoints::Translate( path );
const FileFormatID formatID = FileFormat::Identify( translatedPath );
switch ( formatID )
{
case FILEFORMAT_DICOM: // (hopefully) multi-slice DICOM
volume = VolumeFromFile::ReadDICOM( translatedPath );
break;
case FILEFORMAT_VANDERBILT:
volume = VolumeFromFile::ReadVanderbilt( translatedPath );
break;
case FILEFORMAT_BIORAD:
volume = VolumeFromFile::ReadBioRad( translatedPath );
break;
case FILEFORMAT_ANALYZE_HDR:
volume = VolumeFromFile::ReadAnalyzeHdr( translatedPath, false /*bigendian*/, true /*readData*/ );
break;
case FILEFORMAT_ANALYZE_HDR_BIGENDIAN:
volume = VolumeFromFile::ReadAnalyzeHdr( translatedPath, true /*bigendian*/, true /*readData*/ );
break;
case FILEFORMAT_NIFTI_SINGLEFILE:
volume = VolumeFromFile::ReadNifti( translatedPath, false /*detached*/, true /*readData*/ );
break;
case FILEFORMAT_NIFTI_DETACHED:
volume = VolumeFromFile::ReadNifti( translatedPath, true /*detached*/, true /*readData*/ );
break;
case FILEFORMAT_NRRD:
volume = VolumeFromFile::ReadNRRD( translatedPath );
break;
case FILEFORMAT_NEXIST:
StdErr << "ERROR: could not find file " << path << "\n";
throw ExitException( 1 );
default:
StdErr << "ERROR: unidentified format of file " << path << "\n";
throw ExitException( 1 );
break;
}
if ( ! volume )
{
StdErr << "ERROR: could not read image geometry from " << path << "\n";
throw ExitException( 1 );
}
volume->SetMetaInfo( META_FS_PATH, path );
volume->SetMetaInfo( META_FILEFORMAT_ORIGINAL, FileFormat::Describe( formatID ) );
DebugOutput( 3 ).GetStream().printf( "%s\nRead %d x %d x %d voxels [%f x %f x %f mm total size].\n", path.c_str(),
volume->GetDims()[0], volume->GetDims()[1], volume->GetDims()[2], volume->m_Size[0], volume->m_Size[1], volume->m_Size[2] );
const TypedArray* dataArray = volume->GetData();
if ( ! dataArray )
{
StdErr << "ERROR: could not read image data from " << path << "\n";
throw ExitException( 1 );
}
const Types::DataItemRange range = dataArray->GetRange();
DebugOutput( 3 ).GetStream().printf( "Data type %s, range [%f .. %f]\n", DataTypeName[ dataArray->GetType() ], static_cast<float>( range.m_LowerBound ), static_cast<float>( range.m_UpperBound ) );
return volume;
}
UniformVolume::SmartPtr
VolumeIO::ReadGrid( const std::string& path )
{
UniformVolume::SmartPtr volume( NULL );
const std::string translatedPath = MountPoints::Translate( path );
const FileFormatID formatID = FileFormat::Identify( translatedPath );
try
{
switch ( formatID )
{
case FILEFORMAT_ANALYZE_HDR:
volume = VolumeFromFile::ReadAnalyzeHdr( translatedPath, false /*bigendian*/, false /*readData*/ );
break;
case FILEFORMAT_ANALYZE_HDR_BIGENDIAN:
volume = VolumeFromFile::ReadAnalyzeHdr( translatedPath, true /*bigendian*/, false /*readData*/ );
break;
case FILEFORMAT_NIFTI_SINGLEFILE:
volume = VolumeFromFile::ReadNifti( translatedPath, false /*detached*/, false /*readData*/ );
break;
case FILEFORMAT_NIFTI_DETACHED:
volume = VolumeFromFile::ReadNifti( translatedPath, true /*detached*/, false /*readData*/ );
break;
default: {
// For now, default to full reader for other image file formats
volume = VolumeIO::Read( path );
}
}
}
catch (...) {}
if ( ! volume )
{
StdErr << "ERROR: could not read image from " << path << "\n";
throw ExitException( 1 );
}
DebugOutput( 3 ).GetStream().printf( "%s\nRead %d x %d x %d voxels [%f x %f x %f mm total size].\n", path.c_str(),
volume->GetDims()[0], volume->GetDims()[1], volume->GetDims()[2], volume->m_Size[0], volume->m_Size[1], volume->m_Size[2] );
volume->SetMetaInfo( META_FS_PATH, path );
volume->SetMetaInfo( META_FILEFORMAT_ORIGINAL, FileFormat::Describe( formatID ) );
return volume;
}
UniformVolume::SmartPtr
VolumeIO
::ReadGridOriented( const std::string& path, const char* orientation )
{
UniformVolume::SmartPtr volume( Self::ReadGrid( path ) );
const std::string orientationOriginal = volume->GetMetaInfo( META_IMAGE_ORIENTATION );
if ( orientationOriginal == "" )
{
StdErr << "WARNING: image does not have valid orientation meta information; cannot reorient.\n";
return volume;
}
else
{
if ( orientationOriginal != orientation )
{
DebugOutput( 3 ) << "Reorienting image from '" << orientationOriginal << "' to '" << orientation << "'\n";
return volume->GetReoriented( orientation );
}
}
return volume;
}
UniformVolume::SmartPtr
VolumeIO
::ReadOriented( const std::string& path, const char* orientation )
{
UniformVolume::SmartPtr volume( Self::Read( path ) );
const std::string orientationOriginal = volume->GetMetaInfo( META_IMAGE_ORIENTATION );
if ( orientationOriginal == "" )
{
StdErr << "WARNING: image does not have valid orientation meta information; cannot reorient.\n";
return volume;
}
else
{
if ( orientationOriginal != orientation )
{
DebugOutput( 3 ) << "INFO: reorienting image from '" << orientationOriginal << "' to '" << orientation << "'\n";
return volume->GetReoriented( orientation );
}
}
return volume;
}
void
VolumeIO::Write
( const UniformVolume& volume, const std::string& pathAndFormat )
{
std::string actualPath = pathAndFormat;
FileFormatID fileFormat = FILEFORMAT_UNKNOWN;
const size_t period = pathAndFormat.rfind( '.' );
if ( period != std::string::npos )
{
std::string suffix = pathAndFormat.substr( period );
// check whether we have a compression-related suffix
if ( suffix == ".gz" )
{
// include actual suffix
const size_t period2 = pathAndFormat.rfind( '.', period-1 );
suffix = pathAndFormat.substr( period2, period-period2 );
}
if ( suffix == ".hdr" )
{
fileFormat = FILEFORMAT_ANALYZE_HDR;
}
else
{
if ( suffix == ".img" )
{
fileFormat = FILEFORMAT_NIFTI_DETACHED;
}
else
{
if ( suffix == ".nii" )
{
fileFormat = FILEFORMAT_NIFTI_SINGLEFILE;
}
else
{
if ( suffix == ".mha" )
{
fileFormat = FILEFORMAT_METAIMAGE;
}
else
{
if ( ( suffix == ".nrrd") || (suffix == ".nhdr") )
{
fileFormat = FILEFORMAT_NRRD;
}
}
}
}
}
}
#ifndef _MSC_VER
const size_t colon = pathAndFormat.find( ':' );
if ( colon != std::string::npos )
{
actualPath = pathAndFormat.substr( colon+1 );
const std::string format = pathAndFormat.substr( colon-1 );
if ( format == "ANALYZE" )
{
fileFormat = FILEFORMAT_ANALYZE_HDR;
}
else if ( format == "NIFTI" )
{
fileFormat = FILEFORMAT_NIFTI_SINGLEFILE;
}
else if ( format == "NRRD" )
{
fileFormat = FILEFORMAT_NRRD;
}
else if ( format == "METAIMAGE" )
{
fileFormat = FILEFORMAT_METAIMAGE;
}
}
#endif
if ( fileFormat == FILEFORMAT_UNKNOWN )
{
StdErr << "Fileformat not recognized; writing single-file NIFTI instead.\n";
fileFormat = FILEFORMAT_NIFTI_SINGLEFILE;
}
const std::string absolutePath = FileUtils::GetAbsolutePath( actualPath );
Write( volume, fileFormat, absolutePath );
}
void
VolumeIO::Write
( const UniformVolume& volume, const FileFormatID format, const std::string& path )
{
if ( ! volume.GetData() )
{
StdErr << "ERROR: cannot write volume that does not contain any data.\n";
return;
}
DebugOutput( 3 ).GetStream().printf( "%s\nWriting %d x %d x %d voxels [%f x %f x %f mm total size].\n", path.c_str(),
volume.GetDims()[0], volume.GetDims()[1], volume.GetDims()[2], volume.m_Size[0], volume.m_Size[1], volume.m_Size[2] );
const TypedArray *data = volume.GetData();
if ( data == NULL ) return;
FileUtils::RecursiveMkPrefixDir( path );
const UniformVolume* actualVolume = &volume;
// if volume was reoriented from its original array order, temporarily reorient back and set actual volume to temporary volume.
cmtk::UniformVolume::SmartConstPtr reorientedVolume;
if ( getenv( CMTK_LEGACY_WRITE_IMAGES_RAS ) )
{
DebugOutput( 1 ) << "INFO: forcing legacy RAS image writing due to set environment variable\n";
}
else
{
if ( volume.MetaKeyExists( cmtk::META_IMAGE_ORIENTATION_ORIGINAL ) &&
(volume.GetMetaInfo( cmtk::META_IMAGE_ORIENTATION ) != volume.GetMetaInfo( cmtk::META_IMAGE_ORIENTATION_ORIGINAL ) ) )
{
try
{
reorientedVolume = cmtk::UniformVolume::SmartConstPtr( volume.GetReoriented( volume.GetMetaInfo( cmtk::META_IMAGE_ORIENTATION_ORIGINAL ).c_str() ) );
actualVolume = reorientedVolume;
}
catch ( const AffineXform::MatrixType::SingularMatrixException& )
{
StdErr << "ERROR: singular matrix in cmtk::UniformVolume::GetReoriented(). Writing volume in current orientation.";
}
}
}
switch ( format )
{
case FILEFORMAT_ANALYZE_HDR:
{
VolumeFromFile::WriteAnalyzeHdr( path, *actualVolume );
break;
}
case FILEFORMAT_NIFTI_DETACHED:
case FILEFORMAT_NIFTI_SINGLEFILE:
{
VolumeFromFile::WriteNifti( path, *actualVolume );
break;
}
case FILEFORMAT_METAIMAGE:
{
VolumeFromFile::WriteMetaImage( path, *actualVolume );
break;
}
case FILEFORMAT_NRRD:
{
VolumeFromFile::WriteNRRD( path, *actualVolume );
break;
}
break;
default:
break;
}
// volume.SetMetaInfo( META_FS_PATH, path );
}
VolumeIO::Initializer::Initializer()
{
if ( getenv( "IGS_WRITE_UNCOMPRESSED" ) || getenv( "CMTK_WRITE_UNCOMPRESSED" ) )
VolumeIO::SetWriteCompressedOff();
}
VolumeIO::Initializer VolumeIO::Initializer::Instance;
} // namespace cmtk
|