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 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
|
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: itkNiftiImageIOTest.cxx,v $
Language: C++
Date: $Date: 2010-03-20 20:27:18 $
Version: $Revision: 1.40 $
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.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkNiftiImageIOTest.h"
static void RemoveByteSwapTestFiles(std::string prefix)
{
Remove((prefix+"NiftiLittleEndian.hdr").c_str());
Remove((prefix+"NiftiLittleEndian.img").c_str());
Remove((prefix+"NiftiBigEndian.hdr").c_str());
Remove((prefix+"NiftiBigEndian.img").c_str());
}
//The WriteTestFiles function writes binary data to disk to ensure that both big and little endian files are available.
//This allows all the data necessary to create the images to be stored in source files rather than have separate reference images.
static int WriteTestFiles(std::string prefix)
{
#include "LittleEndian_hdr.h"
struct nifti_1_header NiftiLittleEndian;
memcpy(&NiftiLittleEndian,LittleEndian_hdr,sizeof(NiftiLittleEndian));
NiftiLittleEndian.qform_code=NIFTI_XFORM_UNKNOWN;
NiftiLittleEndian.sform_code=NIFTI_XFORM_UNKNOWN;
strncpy(NiftiLittleEndian.magic,"ni1\0",4);
#include "LittleEndian_img.h"
#include "BigEndian_hdr.h"
struct nifti_1_header NiftiBigEndian;
memcpy(&NiftiBigEndian,BigEndian_hdr,sizeof(NiftiBigEndian));
NiftiBigEndian.qform_code=NIFTI_XFORM_UNKNOWN;
NiftiBigEndian.sform_code=NIFTI_XFORM_UNKNOWN;
strncpy(NiftiBigEndian.magic,"ni1\0",4);
#include "BigEndian_img.h"
//Force to be Nifti-compliant
std::ofstream little_hdr((prefix+"NiftiLittleEndian.hdr").c_str(), std::ios::binary | std::ios::out);
if(!little_hdr.is_open())
return EXIT_FAILURE;
std::cout << "NiftiLittleEndian written" << std::endl;
little_hdr.write(reinterpret_cast<const char *>(LittleEndian_hdr),sizeof(LittleEndian_hdr));
little_hdr.close();
std::ofstream little_img((prefix+"NiftiLittleEndian.img").c_str(), std::ios::binary | std::ios::out);
if(!little_img.is_open())
return EXIT_FAILURE;
little_img.write(reinterpret_cast<const char *>(LittleEndian_img),sizeof(LittleEndian_img));
little_img.close();
std::ofstream big_hdr((prefix+"NiftiBigEndian.hdr").c_str(), std::ios::binary | std::ios::out);
if(!big_hdr.is_open())
return EXIT_FAILURE;
big_hdr.write(reinterpret_cast<const char *>(BigEndian_hdr),sizeof(BigEndian_hdr));
big_hdr.close();
std::ofstream big_img((prefix+"NiftiBigEndian.img").c_str(), std::ios::binary | std::ios::out);
if(!big_img.is_open())
return EXIT_FAILURE;
big_img.write(reinterpret_cast<const char *>(BigEndian_img),sizeof(BigEndian_img));
big_img.close();
return EXIT_SUCCESS;
}
static int TestByteSwap(std::string prefix)
{
int rval;
typedef itk::Image<double, 3> ImageType ;
if(WriteTestFiles(prefix) == -1)
{
return EXIT_FAILURE;
}
ImageType::Pointer little;
ImageType::Pointer big;
try
{
little = ReadImage<ImageType>(prefix+"NiftiLittleEndian.hdr", false);
const std::string fname(prefix+"NiftiBigEndian.hdr");
big = ReadImage<ImageType>(fname, false);
std::cout << "Printing Dictionary" << std::endl;
big->GetMetaDataDictionary().Print(std::cout);
}
catch (itk::ExceptionObject &e)
{
e.Print(std::cerr) ;
RemoveByteSwapTestFiles(prefix);
return EXIT_FAILURE;
}
rval = 0;
try
{
itk::ImageRegionConstIterator<ImageType> littleIter(little,
little->GetLargestPossibleRegion());
itk::ImageRegionConstIterator<ImageType> bigIter(big,
big->GetLargestPossibleRegion());
while(!littleIter.IsAtEnd())
{
if(littleIter.Get() != bigIter.Get())
break;
++littleIter;
++bigIter;
}
if(!littleIter.IsAtEnd() || !bigIter.IsAtEnd())
rval = -1;
}
catch ( itk::ExceptionObject & ex )
{
std::cerr << "Error filling array" << ex << std::endl;
rval= -1;
}
RemoveByteSwapTestFiles(prefix);
return rval;
}
int itkNiftiImageIOTest(int ac, char* av[])
{
itk::ObjectFactoryBase::UnRegisterAllFactories();
itk::NiftiImageIOFactory::RegisterOneFactory();
int rval = 0;
//
// first argument is passing in the writable directory to do all testing
if(ac > 1) {
char *testdir = *++av;
--ac;
itksys::SystemTools::ChangeDirectory(testdir);
}
std::string prefix = "";
if(ac > 1) {
prefix = *++av;
--ac;
}
static bool firstTime = true;
if(firstTime)
{
itk::ObjectFactoryBase::RegisterFactory(itk::NiftiImageIOFactory::New() );
firstTime = false;
}
if(ac > 1) //This is a mechanism for reading unsigned char images for testing.
{
typedef itk::Image<unsigned char, 3> ImageType ;
ImageType::Pointer input;
for(int imagenameindex=1; imagenameindex < ac; imagenameindex++)
{
//std::cout << "Attempting to read " << av[imagenameindex] << std::endl;
try
{
input = ReadImage<ImageType>(std::string(av[imagenameindex]));
}
catch (itk::ExceptionObject &e)
{
e.Print(std::cerr) ;
rval = 1;
}
}
}
else //This is the mechanism for doing internal testing of all data types.
{
int cur_return;
cur_return = MakeNiftiImage<char>();
if(cur_return != 0)
{
std::cerr << "Error writing Nifti file type char" << std::endl;
rval += cur_return;
}
cur_return = MakeNiftiImage<unsigned char>();
if(cur_return != 0)
{
std::cerr << "Error writing Nifti file type unsigned char" << std::endl;
rval += cur_return;
}
cur_return = MakeNiftiImage<short>();
if(cur_return != 0)
{
std::cerr << "Error writing Nifti file type short" << std::endl;
rval += cur_return;
}
cur_return = MakeNiftiImage<unsigned short>();
if(cur_return != 0)
{
std::cerr << "Error writing Nifti file type unsigned short" << std::endl;
rval += cur_return;
}
#ifndef __BORLANDC__
cur_return = MakeNiftiImage<int>();
if(cur_return != 0)
{
std::cerr << "Error writing Nifti file type int" << std::endl;
rval += cur_return;
}
cur_return = MakeNiftiImage<float>();
if(cur_return != 0)
{
std::cerr << "Error writing Nifti file type float" << std::endl;
rval += cur_return;
}
// awaiting a double precision byte swapper
cur_return = MakeNiftiImage<double>();
if(cur_return != 0)
{
std::cerr << "Error writing Nifti file type double" << std::endl;
rval += cur_return;
}
rval += TestByteSwap(prefix);
#endif
}
//Tests added to increase code coverage.
{
itk::NiftiImageIOFactory::Pointer MyFactoryTest=itk::NiftiImageIOFactory::New();
//This was made a protected function. MyFactoryTest->PrintSelf(std::cout,0);
}
return rval;
}
int itkNiftiImageIOTest2(int ac, char* av[])
{
//
// first argument is passing in the writable directory to do all testing
if(ac > 1) {
char *testdir = *++av;
--ac;
itksys::SystemTools::ChangeDirectory(testdir);
}
if(ac != 4)
return EXIT_FAILURE;
char *arg1 = av[1];
char *arg2 = av[2];
char *prefix = av[3];
int test_success = 0;
typedef itk::Image<signed short, 3> ImageType ;
typedef ImageType::Pointer ImagePointer ;
if((strcmp(arg1, "true") == 0) && WriteTestFiles(prefix) == -1)
{
return EXIT_FAILURE;
}
ImagePointer input;
try
{
typedef itk::ImageFileReader<ImageType> ImageReaderType;
itk::NiftiImageIO::Pointer io = itk::NiftiImageIO::New();
ImageReaderType::Pointer imageReader = ImageReaderType::New();
imageReader->SetImageIO(io);
imageReader->SetFileName(arg2);
imageReader->Update();
input = imageReader->GetOutput();
input = ReadImage<ImageType>(std::string(arg2));
}
catch (itk::ExceptionObject &)
{
test_success = 1;
}
if(strcmp(arg1, "true") == 0)
{
return test_success;
}
else
{
return !test_success;
}
}
#ifndef __BORLANDC__
#if defined(_MSC_VER) && _MSC_VER > 1300
template <class ScalarType, unsigned VecLength, unsigned Dimension>
int
TestImageOfVectors(const std::string &fname)
{
const int dimsize = 2;
/** Deformation field pixel type. */
typedef typename itk::Vector<ScalarType,VecLength> FieldPixelType;
/** Deformation field type. */
typedef typename itk::Image<FieldPixelType,Dimension> VectorImageType;
//
// swizzle up a random vector image.
typename VectorImageType::Pointer vi;
typename VectorImageType::RegionType imageRegion;
typename VectorImageType::SizeType size;
typename VectorImageType::IndexType index;
typename VectorImageType::SpacingType spacing;
typename VectorImageType::PointType origin;
typename VectorImageType::DirectionType myDirection;
myDirection.Fill(0.0);
// original test case was destined for failure. NIfTI always writes out 3D
// orientation. The only sensible matrices you could pass in would be of the form
// A B C 0
// D E F 0
// E F G 0
// 0 0 0 1
// anything in the 4th dimension that didn't follow that form would just come up scrambled.
//NOTE: Nifti only reports upto 3D images correctly for direction cosigns. It is implicitly assumed
// that the direction for dimensions 4 or greater come diagonal elements including a 1 in the
// direction matrix.
switch(Dimension)
{
case 1:
myDirection[0][0] = -1.0;
break;
case 2:
myDirection[0][1] = 1.0;
myDirection[1][0] = -1.0;
break;
case 3:
myDirection[0][2] = 1.0;
myDirection[1][0] = -1.0;
myDirection[2][1] = 1.0;
break;
case 4:
myDirection[0][2] = 1.0;
myDirection[1][0] = -1.0;
myDirection[2][1] = 1.0;
myDirection[3][3] = 1.0;
break;
}
std::cout << " === Testing VectorLength: " << VecLength << " Image Dimension " << static_cast<int>(Dimension) << std::endl;
std::cout << "======================== Initialized Direction" << std::endl;
std::cout << myDirection << std::endl;
for(unsigned i = 0; i < Dimension; i++)
{
size[i] = dimsize;
index[i] = 0;
spacing[i] = 1.0;
origin[i] = 0;
}
imageRegion.SetSize(size);
imageRegion.SetIndex(index);
AllocateImageFromRegionAndSpacing(VectorImageType, vi, imageRegion, spacing);
vi->SetOrigin(origin);
vi->SetDirection(myDirection);
typedef itk::ImageRegionIterator<VectorImageType> IteratorType;
typedef itk::ImageRegionConstIterator<VectorImageType> ConstIteratorType;
int dims[7];
int _index[7];
for(unsigned i = 0; i < Dimension; i++)
{
dims[i] = size[i];
}
for(unsigned i = Dimension; i < 7; i++)
{
dims[i] = 1;
}
int incr_value=0;
// for(fillIt.GoToBegin(); !fillIt.IsAtEnd(); ++fillIt)
for(int l = 0; l < dims[6]; l++)
{
_index[6] = l;
for(int m = 0; m < dims[5]; m++)
{
_index[5] = m;
for(int n = 0; n < dims[4]; n++)
{
_index[4] = n;
for(int p = 0; p < dims[3]; p++)
{
_index[3] = p;
for(int i = 0; i < dims[2]; i++)
{
_index[2] = i;
for(int j = 0; j < dims[1]; j++)
{
_index[1] = j;
for(int k = 0; k < dims[0]; k++)
{
_index[0] = k;
FieldPixelType pixel;
float lowrange(100.00),highrange(200.00);
for(unsigned int q = 0; q < VecLength; q++)
{
//pixel[q] = randgen.drand32(lowrange,highrange);
pixel[q] = incr_value++;
lowrange += 100.0;
highrange += 100.0;
}
for(unsigned int q = 0; q < Dimension; q++)
{
index[q] = _index[q];
}
vi->SetPixel(index,pixel);
}
}
}
}
}
}
}
try
{
WriteImage<VectorImageType>(vi,fname);
}
catch(itk::ExceptionObject &ex)
{
std::string message;
message = "Problem found while writing image ";
message += fname; message += "\n";
message += ex.GetLocation(); message += "\n";
message += ex.GetDescription(); std::cout << message << std::endl;
Remove(fname.c_str());
return EXIT_FAILURE;
}
//
// read it back in.
typename VectorImageType::Pointer readback;
try
{
readback = ReadImage<VectorImageType>(fname);
}
catch(itk::ExceptionObject &ex)
{
std::string message;
message = "Problem found while reading image ";
message += fname; message += "\n";
message += ex.GetLocation(); message += "\n";
message += ex.GetDescription(); std::cout << message << std::endl;
Remove(fname.c_str());
return EXIT_FAILURE;
}
bool same = true;
if(readback->GetOrigin() != vi->GetOrigin() )
{
std::cout << "Origin is different: " << readback->GetOrigin() << " != " << vi->GetOrigin() << std::endl;
same = false;
}
if(readback->GetSpacing() != vi->GetSpacing() )
{
std::cout << "Spacing is different: " << readback->GetSpacing() << " != " << vi->GetSpacing() << std::endl;
same = false;
}
for(unsigned int r=0;r<Dimension;r++)
{
for(unsigned int c=0;c<Dimension;c++)
{
if(vcl_abs(readback->GetDirection()[r][c] - vi->GetDirection()[r][c]) > 1e-7 )
{
std::cout << "Direction is different:\n " << readback->GetDirection() << "\n != \n" << vi->GetDirection() << std::endl;
same = false;
break;
}
}
}
std::cout << "Original vector Image ?= vector Image read from disk " << std::endl;
for(int l = 0; l < dims[6]; l++)
{
_index[6] = l;
for(int m = 0; m < dims[5]; m++)
{
_index[5] = m;
for(int n = 0; n < dims[4]; n++)
{
_index[4] = n;
for(int p = 0; p < dims[3]; p++)
{
_index[3] = p;
for(int i = 0; i < dims[2]; i++)
{
_index[2] = i;
for(int j = 0; j < dims[1]; j++)
{
_index[1] = j;
for(int k = 0; k < dims[0]; k++)
{
_index[0] = k;
FieldPixelType p1,p2;
for(unsigned int q = 0; q < Dimension; q++)
{
index[q] = _index[q];
}
p1 = vi->GetPixel(index);
p2 = readback->GetPixel(index);
if(p1 != p2)
{
same = false;
std::cout << p1 << " != " << p2 << " ERROR! " << std::endl;
}
else
{
std::cout << p1 << " == " << p2 << std::endl;
}
}
}
}
}
}
}
}
if(same)
{
Remove(fname.c_str());
}
else
{
std::cout << "Failing image can be found at: " << fname << std::endl;
}
return same ? 0 : EXIT_FAILURE;
}
#endif
#endif
/** Test writing and reading a Vector Image
*/
int itkNiftiImageIOTest3(int ac, char* av[])
{
//
// first argument is passing in the writable directory to do all testing
if(ac > 1)
{
char *testdir = *++av;
itksys::SystemTools::ChangeDirectory(testdir);
}
else
{
return EXIT_FAILURE;
}
int success(0);
#ifndef __BORLANDC__
#if defined(_MSC_VER) && _MSC_VER > 1300
success |= TestImageOfVectors<float,3,1>(std::string("testVectorImage_float_3_1.nii.gz"));
success |= TestImageOfVectors<float,3,2>(std::string("testVectorImage_float_3_2.nii.gz"));
success |= TestImageOfVectors<float,3,3>(std::string("testVectorImage_float_3_3.nii.gz"));
success |= TestImageOfVectors<float,4,3>(std::string("testVectorImage_float_4_3.nii.gz"));
success |= TestImageOfVectors<float,4,4>(std::string("testVectorImage_float_4_4.nii.gz"));
success |= TestImageOfVectors<double,3,3>(std::string("testVectorImage_double_3_3.nii.gz"));
#endif
#endif
return success;
}
typedef itk::Image<unsigned char,3> Test4ImageType;
void
PrintDir(Test4ImageType::DirectionType &dir)
{
for(unsigned i = 0; i < 3; i++)
{
for(unsigned j = 0; j < 3; j++)
{
std::cerr << dir[i][j] << " ";
}
std::cerr << std::endl;
}
}
namespace
{
bool Equal(double a, double b)
{
// actual equality
double diff = a - b;
if(diff == 0.0)
{
return true;
}
// signs match?
if((a < 0.00 && b >= 0.0) ||
(b < 0.0 && a >= 0.0))
{
return false;
}
if(diff < 0.0)
{
diff = -diff;
}
double avg = (a+b)/2.0;
if(avg < 0.0)
{
avg = - avg;
}
if(diff > avg/1000.0)
{
return false;
}
return true;
}
}
int itkNiftiImageIOTest4(int ac, char* av[])
{
//
// first argument is passing in the writable directory to do all testing
if(ac > 1)
{
char *testdir = *++av;
itksys::SystemTools::ChangeDirectory(testdir);
}
else
{
return EXIT_FAILURE;
}
//
Test4ImageType::Pointer test4Image = Test4ImageType::New();
Test4ImageType::RegionType imageRegion;
Test4ImageType::SizeType size;
Test4ImageType::IndexType index;
Test4ImageType::SpacingType spacing;
const unsigned dimsize = 2;
for(unsigned i = 0; i < 3; i++)
{
size[i] = dimsize;
index[i] = 0;
spacing[i] = 1.0;
}
imageRegion.SetSize(size);
imageRegion.SetIndex(index);
AllocateImageFromRegionAndSpacing(Test4ImageType, test4Image, imageRegion, spacing);
test4Image->FillBuffer(0);
Test4ImageType::DirectionType dir;
dir.SetIdentity();
#if 1
// arbitrarily rotate the unit vectors to pick random direction
// cosines;
vnl_random randgen(8775070);
typedef itk::AffineTransform<double,3> TransformType;
typedef itk::Vector<double,3> AxisType;
TransformType::Pointer transform = TransformType::New();
AxisType axis;
axis[0] = 1.0; axis[1] = 0.0; axis[2] = 0.0;
transform->Rotate3D(axis,randgen.drand32(0,3.1415926*2.0));
axis[0] = 0.0; axis[1] = 1.0; axis[2] = 0.0;
transform->Rotate3D(axis,randgen.drand32(0,3.1415926*2.0));
axis[0] = 0.0; axis[1] = 0.0; axis[2] = 1.0;
transform->Rotate3D(axis,randgen.drand32(0,3.1415926*2.0));
TransformType::MatrixType mat = transform->GetMatrix();
for(unsigned i = 0; i < 3; i++)
{
for(unsigned j = 0; j < 3; j++)
{
dir[i][j] = mat[i][j];
}
}
#else
dir =
itk::SpatialOrientationAdapter().ToDirectionCosines(itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_PLI);
#endif
test4Image->SetDirection(dir);
std::string fname("directionsTest.nii.gz");
try
{
WriteImage<Test4ImageType>(test4Image,fname);
}
catch(itk::ExceptionObject &ex)
{
std::string message;
message = "Problem found while writing image ";
message += fname; message += "\n";
message += ex.GetLocation(); message += "\n";
message += ex.GetDescription(); std::cout << message << std::endl;
Remove(fname.c_str());
return EXIT_FAILURE;
}
//
// read it back in.
Test4ImageType::Pointer readback;
try
{
readback = ReadImage<Test4ImageType>(fname);
}
catch(itk::ExceptionObject &ex)
{
std::string message;
message = "Problem found while reading image ";
message += fname; message += "\n";
message += ex.GetLocation(); message += "\n";
message += ex.GetDescription(); std::cout << message << std::endl;
Remove(fname.c_str());
return EXIT_FAILURE;
}
Remove(fname.c_str());
Test4ImageType::DirectionType dir2 = readback->GetDirection();
std::cerr << "Original direction" << std::endl;
PrintDir(dir);
std::cerr << "Retrieved direction" << std::endl;
PrintDir(dir2);
for(unsigned int i = 0; i < 3; i++)
{
for(unsigned int j = 0; j < 3; j++)
{
if(!Equal(dir[i][j],dir2[i][j]))
{
std::cerr << "difference = " << dir[i][j] - dir2[i][j] << std::endl;
return EXIT_FAILURE;
}
}
}
return EXIT_SUCCESS;
}
template <typename PixelType,unsigned typeIndex>
int
SlopeInterceptTest()
{
//
// fill out a nifti image and write it.
const char *filename = "SlopeIntercept.nii";
nifti_image * niftiImage = nifti_simple_init_nim();
niftiImage->fname = (char *)malloc(strlen(filename)+1);
strcpy(niftiImage->fname,filename);
niftiImage->nifti_type = 1;
niftiImage->iname = (char *)malloc(strlen(filename)+1);
strcpy(niftiImage->iname,filename);
niftiImage->dim[0] =
niftiImage->ndim = 3;
niftiImage->nx = niftiImage->dim[1] = 8;
niftiImage->ny = niftiImage->dim[2] = 8;
niftiImage->nz = niftiImage->dim[3] = 4;
niftiImage->nvox = 256;
niftiImage->dx = niftiImage->pixdim[1] =
niftiImage->dy = niftiImage->pixdim[2] =
niftiImage->dz = niftiImage->pixdim[3] = 1.0;
niftiImage->nu = 1;
niftiImage->datatype = typeIndex;
niftiImage->nbyper = sizeof(PixelType);
niftiImage->scl_slope = 1.0/256.0;
niftiImage->scl_inter = 0.0;
niftiImage->sform_code = NIFTI_XFORM_SCANNER_ANAT;
niftiImage->qform_code = NIFTI_XFORM_ALIGNED_ANAT;
niftiImage->qfac = 1;
mat44 matrix;
for(unsigned i = 0; i < 4; i++)
{
for(unsigned j = 0; j < 4; j++)
{
matrix.m[i][j] = (i == j) ? 1.0 : 0.0;
}
}
niftiImage->qto_xyz = matrix;
niftiImage->sto_xyz = matrix;
niftiImage->sto_ijk = matrix;
niftiImage->qto_ijk = matrix;
nifti_mat44_to_quatern(matrix,
&(niftiImage->quatern_b),
&(niftiImage->quatern_c),
&(niftiImage->quatern_d),
&(niftiImage->qoffset_x),
&(niftiImage->qoffset_y),
&(niftiImage->qoffset_z),
0,
0,
0,
&(niftiImage->qfac));
niftiImage->data = malloc(sizeof(PixelType) * 256);
for(unsigned i = 0; i < 256; i++)
{
static_cast<PixelType *>(niftiImage->data)[i] = i;
}
nifti_image_write(niftiImage);
nifti_image_free(niftiImage);
//
// read the image back in
typedef typename itk::Image<float,3> ImageType;
typename ImageType::Pointer image;
try
{
image = ReadImage<ImageType>(std::string(filename));
}
catch(...)
{
Remove(filename);
return EXIT_FAILURE;
}
typedef typename itk::ImageRegionIterator<ImageType> IteratorType;
IteratorType it(image,image->GetLargestPossibleRegion());
it.GoToBegin();
double maxerror = 0.0;
for(unsigned i = 0; i < 256; i++,++it)
{
if(it.IsAtEnd())
{
return EXIT_FAILURE;
}
if(!Equal(it.Value(),static_cast<float>(i)/256.0))
{
// return EXIT_FAILURE;
double error = vcl_abs(it.Value() -
(static_cast<double>(i)/256.0));
if(error > maxerror)
{
maxerror = error;
}
}
}
std::cerr << "Max error " << maxerror << std::endl;
Remove(filename);
return maxerror > 0.00001 ? EXIT_FAILURE : EXIT_SUCCESS;
}
//
// test vector images
int itkNiftiImageIOTest5(int ac, char* av[])
{
//
// first argument is passing in the writable directory to do all testing
if(ac > 1)
{
char *testdir = *++av;
itksys::SystemTools::ChangeDirectory(testdir);
}
else
{
return EXIT_FAILURE;
}
int success(0);
success |= SlopeInterceptTest<unsigned char,NIFTI_TYPE_UINT8>();
success |= SlopeInterceptTest<short,NIFTI_TYPE_INT16>();
success |= SlopeInterceptTest<unsigned short,NIFTI_TYPE_UINT16>();
success |= SlopeInterceptTest<int,NIFTI_TYPE_INT32>();
success |= SlopeInterceptTest<unsigned int,NIFTI_TYPE_UINT32>();
return success;
}
int itkNiftiImageIOTest6(int ac, char *av[])
{
if(ac > 1)
{
char *testdir = *++av;
itksys::SystemTools::ChangeDirectory(testdir);
}
else
{
return EXIT_FAILURE;
}
int success(EXIT_SUCCESS);
typedef itk::VectorImage<double,3> VectorImageType;
VectorImageType::RegionType imageRegion;
VectorImageType::SizeType size;
VectorImageType::IndexType index;
VectorImageType::SpacingType spacing;
VectorImageType::VectorLengthType vecLength(4);
for(unsigned i = 0; i < 3; i++)
{
size[i] = 3;
index[i] = 0;
spacing[i] = 1.0;
}
imageRegion.SetSize(size); imageRegion.SetIndex(index);
VectorImageType::Pointer vecImage;
AllocateVecImageFromRegionAndSpacing(VectorImageType, vecImage, imageRegion, spacing,vecLength);
itk::ImageRegionIterator<VectorImageType>
it(vecImage,vecImage->GetLargestPossibleRegion());
double val(0.0);
for(it.GoToBegin(); it != it.End(); ++it)
{
VectorImageType::PixelType p(vecLength);
for(unsigned i = 0; i < vecLength; i++)
{
p[i] = val;
val++;
}
it.Set(p);
}
const std::string testfname("vectorImage.nii.gz");
VectorImageType::Pointer readback;
try
{
WriteImage<VectorImageType>(vecImage,testfname);
readback = ReadImage<VectorImageType>(testfname);
}
catch(itk::ExceptionObject &err)
{
std::cout << "itkNiftiImageIOTest6" << std::endl
<< "Exception Object caught: " << std::endl
<< err << std::endl;
throw;
}
itk::ImageRegionIterator<VectorImageType>
readbackIt(readback,readback->GetLargestPossibleRegion());
for(it.GoToBegin(),readbackIt.GoToBegin();
it != it.End() && readbackIt != readbackIt.End();
++it, ++readbackIt)
{
VectorImageType::PixelType p(vecLength),
readbackP(vecLength);
p = it.Get();
readbackP = readbackIt.Get();
if(p != readbackP)
{
std::cout << "Pixel mismatch at index "
<< it.GetIndex()
<< " original = "
<< p
<< " read value = "
<< readbackP
<< std::endl;
success = EXIT_FAILURE;
break;
}
}
Remove(testfname.c_str());
return success;
}
/* common code for DTi and sym matrix tests
*
* Could probably be made to fo the image of vector test as well
*/
template <class PixelType, unsigned Dimension>
int
TestImageOfSymMats(const std::string &fname)
{
const int dimsize = 2;
/** Deformation field pixel type. */
// typedef typename itk::DiffusionTenor3D<ScalarType> PixelType;
/** Deformation field type. */
typedef typename itk::Image<PixelType,Dimension> DtiImageType;
//
// swizzle up a random vector image.
typename DtiImageType::Pointer vi;
typename DtiImageType::RegionType imageRegion;
typename DtiImageType::SizeType size;
typename DtiImageType::IndexType index;
typename DtiImageType::SpacingType spacing;
typename DtiImageType::PointType origin;
typename DtiImageType::DirectionType myDirection;
myDirection.Fill(0.0);
// original test case was destined for failure. NIfTI always writes out 3D
// orientation. The only sensible matrices you could pass in would be of the form
// A B C 0
// D E F 0
// E F G 0
// 0 0 0 1
// anything in the 4th dimension that didn't follow that form would just come up scrambled.
//NOTE: Nifti only reports upto 3D images correctly for direction cosigns. It is implicitly assumed
// that the direction for dimensions 4 or greater come diagonal elements including a 1 in the
// direction matrix.
switch(Dimension)
{
case 1:
myDirection[0][0] = -1.0;
break;
case 2:
myDirection[0][1] = 1.0;
myDirection[1][0] = -1.0;
break;
case 3:
myDirection[0][2] = 1.0;
myDirection[1][0] = -1.0;
myDirection[2][1] = 1.0;
break;
case 4:
myDirection[0][2] = 1.0;
myDirection[1][0] = -1.0;
myDirection[2][1] = 1.0;
myDirection[3][3] = 1.0;
break;
}
std::cout << " === Testing DtiImageType: Image Dimension " << static_cast<int>(Dimension) << std::endl;
std::cout << "======================== Initialized Direction" << std::endl;
std::cout << myDirection << std::endl;
for(unsigned i = 0; i < Dimension; i++)
{
size[i] = dimsize;
index[i] = 0;
spacing[i] = 1.0;
origin[i] = 0;
}
imageRegion.SetSize(size);
imageRegion.SetIndex(index);
AllocateImageFromRegionAndSpacing(DtiImageType, vi, imageRegion, spacing);
vi->SetOrigin(origin);
vi->SetDirection(myDirection);
typedef itk::ImageRegionIterator<DtiImageType> IteratorType;
typedef itk::ImageRegionConstIterator<DtiImageType> ConstIteratorType;
int dims[7];
int _index[7];
for(unsigned i = 0; i < Dimension; i++)
{
dims[i] = size[i];
}
for(unsigned i = Dimension; i < 7; i++)
{
dims[i] = 1;
}
int incr_value=0;
// for(fillIt.GoToBegin(); !fillIt.IsAtEnd(); ++fillIt)
for(int l = 0; l < dims[6]; l++)
{
_index[6] = l;
for(int m = 0; m < dims[5]; m++)
{
_index[5] = m;
for(int n = 0; n < dims[4]; n++)
{
_index[4] = n;
for(int p = 0; p < dims[3]; p++)
{
_index[3] = p;
for(int i = 0; i < dims[2]; i++)
{
_index[2] = i;
for(int j = 0; j < dims[1]; j++)
{
_index[1] = j;
for(int k = 0; k < dims[0]; k++)
{
_index[0] = k;
PixelType pixel;
float lowrange(100.00),highrange(200.00);
for(unsigned int q = 0; q < pixel.Size(); q++)
{
//pixel[q] = randgen.drand32(lowrange,highrange);
pixel[q] = incr_value++;
lowrange += 100.0;
highrange += 100.0;
}
for(unsigned int q = 0; q < Dimension; q++)
{
index[q] = _index[q];
}
vi->SetPixel(index,pixel);
}
}
}
}
}
}
}
try
{
WriteImage<DtiImageType>(vi,fname);
}
catch(itk::ExceptionObject &ex)
{
std::string message;
message = "Problem found while writing image ";
message += fname; message += "\n";
message += ex.GetLocation(); message += "\n";
message += ex.GetDescription(); std::cout << message << std::endl;
Remove(fname.c_str());
return EXIT_FAILURE;
}
//
// read it back in.
typename DtiImageType::Pointer readback;
try
{
readback = ReadImage<DtiImageType>(fname);
}
catch(itk::ExceptionObject &ex)
{
std::string message;
message = "Problem found while reading image ";
message += fname; message += "\n";
message += ex.GetLocation(); message += "\n";
message += ex.GetDescription(); std::cout << message << std::endl;
Remove(fname.c_str());
return EXIT_FAILURE;
}
bool same = true;
if(readback->GetOrigin() != vi->GetOrigin() )
{
std::cout << "Origin is different: " << readback->GetOrigin() << " != " << vi->GetOrigin() << std::endl;
same = false;
}
if(readback->GetSpacing() != vi->GetSpacing() )
{
std::cout << "Spacing is different: " << readback->GetSpacing() << " != " << vi->GetSpacing() << std::endl;
same = false;
}
for(unsigned int r=0;r<Dimension;r++)
{
for(unsigned int c=0;c<Dimension;c++)
{
if(vcl_abs(readback->GetDirection()[r][c] - vi->GetDirection()[r][c]) > 1e-7 )
{
std::cout << "Direction is different:\n " << readback->GetDirection() << "\n != \n" << vi->GetDirection() << std::endl;
same = false;
break;
}
}
}
std::cout << "Original Image ?= Image read from disk " << std::endl;
for(int l = 0; l < dims[6]; l++)
{
_index[6] = l;
for(int m = 0; m < dims[5]; m++)
{
_index[5] = m;
for(int n = 0; n < dims[4]; n++)
{
_index[4] = n;
for(int p = 0; p < dims[3]; p++)
{
_index[3] = p;
for(int i = 0; i < dims[2]; i++)
{
_index[2] = i;
for(int j = 0; j < dims[1]; j++)
{
_index[1] = j;
for(int k = 0; k < dims[0]; k++)
{
_index[0] = k;
PixelType p1,p2;
for(unsigned int q = 0; q < Dimension; q++)
{
index[q] = _index[q];
}
p1 = vi->GetPixel(index);
p2 = readback->GetPixel(index);
if(p1 != p2)
{
same = false;
std::cout << p1 << " != " << p2 << " ERROR! " << std::endl;
}
else
{
std::cout << p1 << " == " << p2 << std::endl;
}
}
}
}
}
}
}
}
if(same)
{
Remove(fname.c_str());
}
else
{
std::cout << "Failing image can be found at: " << fname << std::endl;
}
return same ? 0 : EXIT_FAILURE;
}
/** Test writing and reading a Vector Image
*/
int itkNiftiImageIOTest7(int ac, char* av[])
{
//
// first argument is passing in the writable directory to do all testing
if(ac > 1)
{
char *testdir = *++av;
itksys::SystemTools::ChangeDirectory(testdir);
}
else
{
return EXIT_FAILURE;
}
int success(0);
success |= TestImageOfSymMats<itk::DiffusionTensor3D<float>,1>( std::string("testDtiImage_float_1.nii.gz"));
success |= TestImageOfSymMats<itk::DiffusionTensor3D<float>,2>( std::string("testDtiImage_float_2.nii.gz"));
success |= TestImageOfSymMats<itk::DiffusionTensor3D<float>,3>( std::string("testDtiImage_float_3.nii.gz"));
success |= TestImageOfSymMats<itk::DiffusionTensor3D<float>,4>( std::string("testDtiImage_float_4.nii.gz"));
success |= TestImageOfSymMats<itk::DiffusionTensor3D<double>,3>(std::string("testDtiImage_double_3.nii.gz"));
return success;
}
int itkNiftiImageIOTest8(int ac, char *av[])
{
if(ac > 1)
{
char *testdir = *++av;
itksys::SystemTools::ChangeDirectory(testdir);
}
else
{
return EXIT_FAILURE;
}
int success(0);
//only 3,4,5,6 as supported in itkImageIOBase
success |= TestImageOfSymMats<itk::SymmetricSecondRankTensor<float,3>,1>(std::string("testSymImage_float_2_1.nii.gz"));
success |= TestImageOfSymMats<itk::SymmetricSecondRankTensor<float,3>,2>(std::string("testSymImage_float_2_2.nii.gz"));
success |= TestImageOfSymMats<itk::SymmetricSecondRankTensor<float,3>,3>(std::string("testSymImage_float_2_3.nii.gz"));
success |= TestImageOfSymMats<itk::SymmetricSecondRankTensor<float,3>,4>(std::string("testSymImage_float_2_4.nii.gz"));
//only test some of the others
success |= TestImageOfSymMats<itk::SymmetricSecondRankTensor<float,4>,3>(std::string("testSymImage_float_3_3.nii.gz"));
success |= TestImageOfSymMats<itk::SymmetricSecondRankTensor<float,5>,3>(std::string("testSymImage_float_3_3.nii.gz"));
success |= TestImageOfSymMats<itk::SymmetricSecondRankTensor<float,6>,3>(std::string("testSymImage_float_3_3.nii.gz"));
return success;
}
|