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 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
|
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkNiftiImageIO.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 "itkNiftiImageIO.h"
#include "itkIOCommon.h"
#include "itkExceptionObject.h"
#include "itkByteSwapper.h"
#include "itkMetaDataObject.h"
#include "itkSpatialOrientationAdapter.h"
#include "itkNumericTraits.h"
#include <itksys/SystemTools.hxx>
#include <vnl/vnl_math.h>
#include "itk_zlib.h"
#include <stdio.h>
#include <stdlib.h>
#include <vector>
namespace itk
{
//#define __USE_VERY_VERBOSE_NIFTI_DEBUGGING__
#if defined(__USE_VERY_VERBOSE_NIFTI_DEBUGGING__)
namespace
{
static int print_hex_vals(
char const * const data,
const int nbytes,
FILE * const fp )
{
int c;
if ( !data || nbytes < 1 || !fp )
{
return -1;
}
fputs("0x", fp);
for ( c = 0; c < nbytes; c++ )
{
fprintf(fp, " %x", data[c]);
}
return 0;
}
static char *str_intent(unsigned int intent)
{
switch(intent)
{
case NIFTI_INTENT_NONE:
return "NIFTI_INTENT_NONE";
case NIFTI_INTENT_CORREL:
return "NIFTI_INTENT_CORREL";
case NIFTI_INTENT_TTEST:
return "NIFTI_INTENT_TTEST";
case NIFTI_INTENT_FTEST:
return "NIFTI_INTENT_FTEST";
case NIFTI_INTENT_ZSCORE:
return "NIFTI_INTENT_ZSCORE";
case NIFTI_INTENT_CHISQ:
return "NIFTI_INTENT_CHISQ";
case NIFTI_INTENT_BETA:
return "NIFTI_INTENT_BETA";
case NIFTI_INTENT_BINOM:
return "NIFTI_INTENT_BINOM";
case NIFTI_INTENT_GAMMA:
return "NIFTI_INTENT_GAMMA";
case NIFTI_INTENT_POISSON:
return "NIFTI_INTENT_POISSON";
case NIFTI_INTENT_NORMAL:
return "NIFTI_INTENT_NORMAL";
case NIFTI_INTENT_FTEST_NONC:
return "NIFTI_INTENT_FTEST_NONC";
case NIFTI_INTENT_CHISQ_NONC:
return "NIFTI_INTENT_CHISQ_NONC";
case NIFTI_INTENT_LOGISTIC:
return "NIFTI_INTENT_LOGISTIC";
case NIFTI_INTENT_LAPLACE:
return "NIFTI_INTENT_LAPLACE";
case NIFTI_INTENT_UNIFORM:
return "NIFTI_INTENT_UNIFORM";
case NIFTI_INTENT_TTEST_NONC:
return "NIFTI_INTENT_TTEST_NONC";
case NIFTI_INTENT_WEIBULL:
return "NIFTI_INTENT_WEIBULL";
case NIFTI_INTENT_CHI:
return "NIFTI_INTENT_CHI";
case NIFTI_INTENT_INVGAUSS:
return "NIFTI_INTENT_INVGAUSS";
case NIFTI_INTENT_EXTVAL:
return "NIFTI_INTENT_EXTVAL";
case NIFTI_INTENT_PVAL:
return "NIFTI_INTENT_PVAL";
case NIFTI_INTENT_LOGPVAL:
return "NIFTI_INTENT_LOGPVAL";
case NIFTI_INTENT_LOG10PVAL:
return "NIFTI_INTENT_LOG10PVAL";
case NIFTI_INTENT_ESTIMATE:
return "NIFTI_INTENT_ESTIMATE";
case NIFTI_INTENT_LABEL:
return "NIFTI_INTENT_LABEL";
case NIFTI_INTENT_NEURONAME:
return "NIFTI_INTENT_NEURONAME";
case NIFTI_INTENT_GENMATRIX:
return "NIFTI_INTENT_GENMATRIX";
case NIFTI_INTENT_SYMMATRIX:
return "NIFTI_INTENT_SYMMATRIX";
case NIFTI_INTENT_DISPVECT:
return "NIFTI_INTENT_DISPVECT";
case NIFTI_INTENT_VECTOR:
return "NIFTI_INTENT_VECTOR";
case NIFTI_INTENT_POINTSET:
return "NIFTI_INTENT_POINTSET";
case NIFTI_INTENT_TRIANGLE:
return "NIFTI_INTENT_TRIANGLE";
case NIFTI_INTENT_QUATERNION:
return "NIFTI_INTENT_QUATERNION";
case NIFTI_INTENT_DIMLESS:
return "NIFTI_INTENT_DIMLESS";
default:
return "UNKNOWN_INTENT";
}
}
/*----------------------------------------------------------------------*/
/*! display the contents of the nifti_1_header (send to stdout)
*--------------------------------------------------------------------*/
static int DumpNiftiHeader( const std::string &fname )
{
int c;
nifti_1_header *hp;
int swap;
hp = nifti_read_header(fname.c_str(),&swap,true);
fputs( "-------------------------------------------------------\n",
stderr );
if ( !hp )
{
fputs(" ** no nifti_1_header to display!\n",stderr);
return 1;
}
fprintf(stderr," nifti_1_header :\n"
" sizeof_hdr = %d\n"
" data_type[10] = ", hp->sizeof_hdr);
print_hex_vals(hp->data_type, 10, stderr);
fprintf(stderr, "\n"
" db_name[18] = ");
print_hex_vals(hp->db_name, 18, stderr);
fprintf(stderr, "\n"
" extents = %d\n"
" session_error = %d\n"
" regular = 0x%x\n"
" dim_info = 0x%x\n",
hp->extents, hp->session_error, hp->regular, hp->dim_info );
fprintf(stderr, " dim[8] =");
for ( c = 0; c < 8; c++ ) fprintf(stderr," %d", hp->dim[c]);
fprintf(stderr, "\n"
" intent_p1 = %f\n"
" intent_p2 = %f\n"
" intent_p3 = %f\n"
" intent_code = %s\n"
" datatype = %d\n"
" bitpix = %d\n"
" slice_start = %d\n"
" pixdim[8] =",
hp->intent_p1, hp->intent_p2, hp->intent_p3,
str_intent(hp->intent_code),
hp->datatype, hp->bitpix, hp->slice_start);
/* break pixdim over 2 lines */
for ( c = 0; c < 4; c++ ) fprintf(stderr," %f", hp->pixdim[c]);
fprintf(stderr, "\n ");
for ( c = 4; c < 8; c++ ) fprintf(stderr," %f", hp->pixdim[c]);
fprintf(stderr, "\n"
" vox_offset = %f\n"
" scl_slope = %f\n"
" scl_inter = %f\n"
" slice_end = %d\n"
" slice_code = %d\n"
" xyzt_units = 0x%x\n"
" cal_max = %f\n"
" cal_min = %f\n"
" slice_duration = %f\n"
" toffset = %f\n"
" glmax = %d\n"
" glmin = %d\n",
hp->vox_offset, hp->scl_slope, hp->scl_inter, hp->slice_end,
hp->slice_code, hp->xyzt_units, hp->cal_max, hp->cal_min,
hp->slice_duration, hp->toffset, hp->glmax, hp->glmin);
fprintf(stderr,
" descrip = '%.80s'\n"
" aux_file = '%.24s'\n"
" qform_code = %d\n"
" sform_code = %d\n"
" quatern_b = %f\n"
" quatern_c = %f\n"
" quatern_d = %f\n"
" qoffset_x = %f\n"
" qoffset_y = %f\n"
" qoffset_z = %f\n"
" srow_x[4] = %f, %f, %f, %f\n"
" srow_y[4] = %f, %f, %f, %f\n"
" srow_z[4] = %f, %f, %f, %f\n"
" intent_name = '%-.16s'\n"
" magic = '%-.4s'\n",
hp->descrip, hp->aux_file, hp->qform_code, hp->sform_code,
hp->quatern_b, hp->quatern_c, hp->quatern_d,
hp->qoffset_x, hp->qoffset_y, hp->qoffset_z,
hp->srow_x[0], hp->srow_x[1], hp->srow_x[2], hp->srow_x[3],
hp->srow_y[0], hp->srow_y[1], hp->srow_y[2], hp->srow_y[3],
hp->srow_z[0], hp->srow_z[1], hp->srow_z[2], hp->srow_z[3],
hp->intent_name, hp->magic);
fputs("-------------------------------------------------------\n",
stderr );
fflush(stderr);
return 0;
}
static void dumpdata(const void *x)
{
std::cerr << "----------------------" << std::endl;
// typedef const float (*itkarray)[1][2][2][2][3];
const float *a = (const float *)x;
for(unsigned int i = 0; i < 24; i++) // t
{
std::cerr << a[i] << std::endl;
}
}
}
#else
#define dumpdata(x)
#endif // #if defined(__USE_VERY_VERBOSE_NIFTI_DEBUGGING__)
// returns an ordering array for converting upper triangular symmetric matrix
// to lower triangular symmetric matrix
int *
UpperToLowerOrder(int dim)
{
int **mat = new int *[dim];
for(int i = 0; i < dim; i++)
{
mat[i] = new int[dim];
}
// fill in
int index(0);
for(int i = 0; i < dim; i++)
{
for(int j = i; j < dim; j++)
{
mat[i][j] = index;
mat[j][i] = index;
index++;
}
}
int *rval = new int[index+1];
int index2(0);
for(int i = 0; i < dim; i++)
{
for(int j = 0; j <= i; j++,index2++)
{
rval[index2] = mat[i][j];
}
}
rval[index2] = -1;
for(int i = 0; i < dim; i++)
{
delete [] mat[i];
}
delete [] mat;
return rval;
}
// returns an ordering array for converting lower triangular symmetric matrix
// to upper triangular symmetric matrix
int *
LowerToUpperOrder(int dim)
{
int **mat = new int *[dim];
for(int i = 0; i < dim; i++)
{
mat[i] = new int[dim];
}
// fill in
int index(0);
for(int i = 0; i < dim; i++)
{
for(int j = 0; j <= i; j++,index++)
{
mat[i][j] = index;
mat[j][i] = index;
}
}
int *rval = new int[index+1];
int index2(0);
for(int i = 0; i < dim; i++)
{
for(int j = i; j < dim; j++,index2++)
{
rval[index2] = mat[i][j];
}
}
rval[index2] = -1;
for(int i = 0; i < dim; i++)
{
delete [] mat[i];
}
delete [] mat;
return rval;
}
// compute the rank of the symmetric matrix from
// the count of the triangular matrix elements
int SymMatDim(int count)
{
int dim = 0;
int row = 1;
while(count > 0)
{
count -= row;
dim++;
row++;
}
return dim;
}
ImageIORegion
NiftiImageIO
::GenerateStreamableReadRegionFromRequestedRegion(const ImageIORegion & requestedRegion ) const
{
return requestedRegion;
}
NiftiImageIO::NiftiImageIO():
m_NiftiImage(0),
m_RescaleSlope(1.0),
m_RescaleIntercept(0.0),
m_OnDiskComponentType(UNKNOWNCOMPONENTTYPE),
m_LegacyAnalyze75Mode(false)
{
this->SetNumberOfDimensions(3);
nifti_set_debug_level(0); // suppress error messages
this->AddSupportedWriteExtension(".nia");
this->AddSupportedWriteExtension(".nii");
this->AddSupportedWriteExtension(".nii.gz");
this->AddSupportedReadExtension(".nia");
this->AddSupportedReadExtension(".nii");
this->AddSupportedReadExtension(".nii.gz");
this->AddSupportedWriteExtension(".hdr");
this->AddSupportedWriteExtension(".img");
this->AddSupportedWriteExtension(".img.gz");
this->AddSupportedReadExtension(".hdr");
this->AddSupportedReadExtension(".img");
this->AddSupportedReadExtension(".img.gz");
}
NiftiImageIO::~NiftiImageIO()
{
nifti_image_free(this->m_NiftiImage);
}
void
NiftiImageIO
::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "LegacyAnalyze75Mode: " << this->m_LegacyAnalyze75Mode << std::endl;
}
bool
NiftiImageIO
::CanWriteFile(const char * FileNameToWrite)
{
const int ValidFileNameFound=nifti_is_complete_filename(FileNameToWrite) > 0;
return ValidFileNameFound;
}
bool
NiftiImageIO::MustRescale()
{
return vcl_abs(this->m_RescaleSlope) > vcl_numeric_limits<double>::epsilon() &&
(vcl_abs(this->m_RescaleSlope-1.0) > vcl_numeric_limits<double>::epsilon() ||
vcl_abs(this->m_RescaleIntercept) > vcl_numeric_limits<double>::epsilon());
}
// Internal function to rescale pixel according to Rescale Slope/Intercept
template<class TBuffer>
void RescaleFunction(TBuffer* buffer,
double slope,
double intercept,
size_t size)
{
for(unsigned int i=0; i<size; i++)
{
double tmp = static_cast<double>(buffer[i]) * slope;
tmp += intercept;
buffer[i] = static_cast<TBuffer>(tmp);
}
}
template <typename PixelType>
void
CastCopy(float *to,void *from, size_t pixelcount)
{
PixelType *_from = static_cast<PixelType *>(from);
for(unsigned i = 0; i < pixelcount; i++)
{
to[i] = static_cast<float>(_from[i]);
}
}
void NiftiImageIO::Read(void* buffer)
{
void *data = 0;
ImageIORegion regionToRead = this->GetIORegion();
ImageIORegion::SizeType size = regionToRead.GetSize();
ImageIORegion::IndexType start = regionToRead.GetIndex();
int numElts = 1;
int _origin[7];
int _size[7];
unsigned int i;
for(i = 0; i < start.size(); i++)
{
_origin[i] = static_cast<int>( start[i] );
_size[i] = static_cast<int>( size[i] );
numElts *= _size[i];
}
for(; i < 7; i++)
{
_origin[i] = 0;
_size[i] = 1;
}
unsigned int numComponents = this->GetNumberOfComponents();
//
// special case for images of vector pixels
if(numComponents > 1 && this->GetPixelType() != COMPLEX)
{
// nifti always sticks vec size in dim 4, so have to shove
// other dims out of the way
_size[6] = _size[5];
_size[5] = _size[4];
// sizes = x y z t vecsize
_size[4] = numComponents;
}
// Free memory if any was occupied already (incase of re-using the IO filter).
if (this->m_NiftiImage != NULL)
{
nifti_image_free(this->m_NiftiImage);
}
//
// allocate nifti image...
this->m_NiftiImage = nifti_image_read(this->GetFileName(),false);
if (this->m_NiftiImage == NULL)
{
itkExceptionMacro(<< "nifti_image_read (just header) failed for file: "
<< this->GetFileName());
}
//
// decide whether to read whole region or subregion, by stepping
// thru dims and comparing them to requested sizes
for(i = 0; i < this->GetNumberOfDimensions(); i++)
{
if(this->m_NiftiImage->dim[i+1] != _size[i])
{
break;
}
}
// if all dimensions match requested size, just read in
// all data as a block
if(i == this->GetNumberOfDimensions())
{
if(nifti_image_load(this->m_NiftiImage) == -1)
{
itkExceptionMacro(<< "nifti_image_load failed for file: "
<< this->GetFileName());
}
data = this->m_NiftiImage->data;
}
else
{
// read in a subregion
if(nifti_read_subregion_image(this->m_NiftiImage,
_origin,
_size,
&data) == -1 || this->m_NiftiImage == NULL)
{
itkExceptionMacro(<< "nifti_read_subregion_image failed for file: "
<< this->GetFileName());
}
}
unsigned int pixelSize = this->m_NiftiImage->nbyper;
//
// if we're going to have to rescale pixels, and the on-disk
// pixel type is different than the pixel type reported to
// ImageFileReader, we have to up-promote the data to float
// before doing the rescale.
//
if(this->MustRescale() &&
this->m_ComponentType != this->m_OnDiskComponentType)
{
pixelSize =
static_cast< unsigned int >( this->GetNumberOfComponents() ) *
static_cast< unsigned int >( sizeof(float) );
// Deal with correct management of 64bits platforms
const size_t imageSizeInComponents =
static_cast< size_t >( this->GetImageSizeInComponents() );
//
// allocate new buffer for floats. Malloc instead of new to
// be consistent with allocation used in niftilib
float *_data =
static_cast<float *>
(malloc( imageSizeInComponents * sizeof(float)));
switch(this->m_OnDiskComponentType)
{
case CHAR:
CastCopy<char>(_data,data, imageSizeInComponents);
break;
case UCHAR:
CastCopy<unsigned char>(_data,data, imageSizeInComponents);
break;
case SHORT:
CastCopy<short>(_data,data, imageSizeInComponents);
break;
case USHORT:
CastCopy<unsigned short>(_data,data, imageSizeInComponents);
break;
case INT:
CastCopy<int>(_data,data, imageSizeInComponents);
break;
case UINT:
CastCopy<unsigned int>(_data,data, imageSizeInComponents);
break;
case LONG:
CastCopy<long>(_data,data, imageSizeInComponents);
break;
case ULONG:
CastCopy<unsigned long>(_data,data, imageSizeInComponents);
break;
case FLOAT:
itkExceptionMacro(<< "FLOAT pixels do not need Casting to float");
break;
case DOUBLE:
itkExceptionMacro(<< "DOUBLE pixels do not need Casting to float");
break;
case UNKNOWNCOMPONENTTYPE:
itkExceptionMacro(<< "Bad OnDiskComponentType UNKNOWNCOMPONENTTYPE");
}
//
// we're replacing the data pointer, so if it was allocated
// in nifti_read_subregion_image, free the old data here
if(data != this->m_NiftiImage->data)
{
free(data);
}
data = _data;
}
//
// if single or complex, nifti layout == itk layout
if(numComponents == 1 ||
this->GetPixelType() == COMPLEX ||
this->GetPixelType() == RGB ||
this->GetPixelType() == RGBA)
{
const size_t NumBytes= numElts * pixelSize;
memcpy(buffer, data, NumBytes);
//
// if read_subregion was called it allocates a buffer that needs to be
// freed.
if(data != this->m_NiftiImage->data)
{
free(data);
}
}
else
{
// otherwise nifti is x y z t vec l m 0, itk is
// vec x y z t l m o
const char *niftibuf = (const char *)data;
char *itkbuf = (char *)buffer;
const unsigned int rowdist=this->m_NiftiImage->dim[1];
const unsigned int slicedist=rowdist*this->m_NiftiImage->dim[2];
const unsigned int volumedist=slicedist*this->m_NiftiImage->dim[3];
const unsigned int seriesdist=volumedist*this->m_NiftiImage->dim[4];
//
// as per ITK bug 0007485
// NIfTI is lower triangular, ITK is upper triangular.
int *vecOrder;
if(this->GetPixelType() == ImageIOBase::DIFFUSIONTENSOR3D ||
this->GetPixelType() == ImageIOBase::SYMMETRICSECONDRANKTENSOR)
{
// vecOrder = LowerToUpperOrder(SymMatDim(numComponents));
vecOrder = UpperToLowerOrder(SymMatDim(numComponents));
}
else
{
vecOrder = new int[numComponents];
for(i = 0; i < numComponents; i++)
{
vecOrder[i] = i;
}
}
for(int t = 0; t < this->m_NiftiImage->dim[4]; t++)
{
for(int z = 0; z < this->m_NiftiImage->dim[3]; z++)
{
for(int y = 0; y < this->m_NiftiImage->dim[2]; y++)
{
for(int x = 0; x < this->m_NiftiImage->dim[1]; x++)
{
for(unsigned int c=0;c< numComponents; c++)
{
const unsigned int nifti_index=(c*seriesdist+volumedist*t + slicedist*z + rowdist*y + x)*pixelSize;
const unsigned int itk_index=((volumedist*t + slicedist*z + rowdist*y + x)*numComponents + vecOrder[c])*pixelSize;
memcpy(itkbuf+itk_index,niftibuf+nifti_index,pixelSize);
}
}
}
}
}
delete [] vecOrder;
dumpdata(data);
dumpdata(buffer);
// if read_subregion was called it allocates a buffer that needs to be
// freed.
if(data != this->m_NiftiImage->data)
{
free(data);
}
}
// If the scl_slope field is nonzero, then rescale each voxel value in the
// dataset.
// Complete description of can be found in nifti1.h under "DATA SCALING"
if(this->MustRescale())
{
switch(this->m_ComponentType)
{
case CHAR:
RescaleFunction(static_cast<char *>(buffer),
this->m_RescaleSlope,
this->m_RescaleIntercept,numElts);
break;
case UCHAR:
RescaleFunction(static_cast<unsigned char *>(buffer),
this->m_RescaleSlope,
this->m_RescaleIntercept,numElts);
break;
case SHORT:
RescaleFunction(static_cast<short *>(buffer),
this->m_RescaleSlope,
this->m_RescaleIntercept,numElts);
break;
case USHORT:
RescaleFunction(static_cast<unsigned short *>(buffer),
this->m_RescaleSlope,
this->m_RescaleIntercept,numElts);
break;
case INT:
RescaleFunction(static_cast<int *>(buffer),
this->m_RescaleSlope,
this->m_RescaleIntercept,numElts);
break;
case UINT:
RescaleFunction(static_cast<unsigned int *>(buffer),
this->m_RescaleSlope,
this->m_RescaleIntercept,numElts);
break;
case LONG:
RescaleFunction(static_cast<long *>(buffer),
this->m_RescaleSlope,
this->m_RescaleIntercept,numElts);
break;
case ULONG:
RescaleFunction(static_cast<unsigned long *>(buffer),
this->m_RescaleSlope,
this->m_RescaleIntercept,numElts);
break;
case FLOAT:
RescaleFunction(static_cast<float *>(buffer),
this->m_RescaleSlope,
this->m_RescaleIntercept,numElts);
break;
case DOUBLE:
RescaleFunction(static_cast<double *>(buffer),
this->m_RescaleSlope,
this->m_RescaleIntercept,numElts);
break;
default:
if(this->GetPixelType() == SCALAR)
{
itkExceptionMacro(<< "Datatype: "
<< this->GetComponentTypeAsString(this->m_ComponentType)
<< " not supported");
}
}
}
}
// This method will only test if the header looks like an
// Nifti Header. Some code is redundant with ReadImageInformation
// a StateMachine could provide a better implementation
bool
NiftiImageIO
::CanReadFile( const char* FileNameToRead )
{
// is_nifti_file returns
// > 0 for a nifti file
// == 0 for an analyze file,
// < 0 for an error,
// if the return test is >= 0, nifti will read analyze files
//return is_nifti_file(FileNameToRead) > 0;
const int image_FTYPE=is_nifti_file(FileNameToRead);
if(image_FTYPE>0)
{
return true;
}
else if (image_FTYPE == 0 && ( this->GetLegacyAnalyze75Mode() == true ))
{
return true;
}
/* image_FTYPE < 0 */
return false;
}
// This method adds the available header information to the
// metadata dictionary.
void NiftiImageIO::SetImageIOMetadataFromNIfTI()
{
int swap = 0;
nifti_1_header *header = nifti_read_header(this->GetFileName(), &swap, true);
if (header)
{
// Encapsulate as many header information as possible.
MetaDataDictionary &thisDic = this->GetMetaDataDictionary();
std::ostringstream dim_info;
dim_info << header->dim_info;
EncapsulateMetaData<std::string>(thisDic, "dim_info", dim_info.str());
for (int idx = 0; idx < 8; idx++)
{
std::ostringstream dim;
dim << header->dim[idx];
std::ostringstream dimKey;
dimKey << "dim[" << idx << "]";
EncapsulateMetaData<std::string>(thisDic, dimKey.str(), dim.str());
}
std::ostringstream intent_p1;
intent_p1 << header->intent_p1;
EncapsulateMetaData<std::string>(thisDic, "intent_p1", intent_p1.str());
std::ostringstream intent_p2;
intent_p2 << header->intent_p2;
EncapsulateMetaData<std::string>(thisDic, "intent_p2", intent_p2.str());
std::ostringstream intent_p3;
intent_p3 << header->intent_p3;
EncapsulateMetaData<std::string>(thisDic, "intent_p3", intent_p3.str());
std::ostringstream intent_code;
intent_code << header->intent_code;
EncapsulateMetaData<std::string>(thisDic, "intent_code", intent_code.str());
std::ostringstream datatype;
datatype << header->datatype;
EncapsulateMetaData<std::string>(thisDic, "datatype", datatype.str());
std::ostringstream bitpix;
bitpix << header->bitpix;
EncapsulateMetaData<std::string>(thisDic, "bitpix", bitpix.str());
std::ostringstream slice_start;
slice_start << header->slice_start;
EncapsulateMetaData<std::string>(thisDic, "slice_start", slice_start.str());
for (int idx = 0; idx < 8; idx++)
{
std::ostringstream pixdim;
pixdim << header->pixdim[idx];
std::ostringstream pixdimKey;
pixdimKey << "pixdim[" << idx << "]";
EncapsulateMetaData<std::string>(thisDic, pixdimKey.str(), pixdim.str());
}
std::ostringstream vox_offset;
vox_offset << header->vox_offset;
EncapsulateMetaData<std::string>(thisDic, "vox_offset", vox_offset.str());
std::ostringstream scl_slope;
scl_slope << header->scl_slope;
EncapsulateMetaData<std::string>(thisDic, "scl_slope", scl_slope.str());
std::ostringstream scl_inter;
scl_inter << header->scl_inter;
EncapsulateMetaData<std::string>(thisDic, "scl_inter", scl_inter.str());
std::ostringstream slice_end;
slice_end << header->slice_end;
EncapsulateMetaData<std::string>(thisDic, "slice_end", slice_end.str());
std::ostringstream slice_code;
slice_code << header->slice_code;
EncapsulateMetaData<std::string>(thisDic, "slice_code", slice_code.str());
std::ostringstream xyzt_units;
xyzt_units << header->xyzt_units;
EncapsulateMetaData<std::string>(thisDic, "xyzt_units", xyzt_units.str());
std::ostringstream cal_max;
cal_max << header->cal_max;
EncapsulateMetaData<std::string>(thisDic, "cal_max", cal_max.str());
std::ostringstream cal_min;
cal_min << header->cal_min;
EncapsulateMetaData<std::string>(thisDic, "cal_min", cal_min.str());
std::ostringstream slice_duration;
slice_duration << header->slice_duration;
EncapsulateMetaData<std::string>(thisDic, "slice_duration", slice_duration.str());
std::ostringstream toffset;
toffset << header->toffset;
EncapsulateMetaData<std::string>(thisDic, "toffset", toffset.str());
std::ostringstream descrip;
descrip << header->descrip;
EncapsulateMetaData<std::string>(thisDic, "descrip", descrip.str());
std::ostringstream aux_file;
aux_file << header->aux_file;
EncapsulateMetaData<std::string>(thisDic, "aux_file", aux_file.str());
std::ostringstream qform_code;
qform_code << header->qform_code;
EncapsulateMetaData<std::string>(thisDic, "qform_code", qform_code.str());
std::ostringstream sform_code;
sform_code << header->sform_code;
EncapsulateMetaData<std::string>(thisDic, "sform_code", sform_code.str());
std::ostringstream quatern_b;
quatern_b << header->quatern_b;
EncapsulateMetaData<std::string>(thisDic, "quatern_b", quatern_b.str());
std::ostringstream quatern_c;
quatern_c << header->quatern_c;
EncapsulateMetaData<std::string>(thisDic, "quatern_c", quatern_c.str());
std::ostringstream quatern_d;
quatern_d << header->quatern_d;
EncapsulateMetaData<std::string>(thisDic, "quatern_d", quatern_d.str());
std::ostringstream qoffset_x;
qoffset_x << header->qoffset_x;
EncapsulateMetaData<std::string>(thisDic, "qoffset_x", qoffset_x.str());
std::ostringstream qoffset_y;
qoffset_y << header->qoffset_y;
EncapsulateMetaData<std::string>(thisDic, "qoffset_y", qoffset_y.str());
std::ostringstream qoffset_z;
qoffset_z << header->qoffset_z;
EncapsulateMetaData<std::string>(thisDic, "qoffset_z", qoffset_z.str());
std::ostringstream srow_x;
srow_x << header->srow_x[0] << " " << header->srow_x[1] << " " << header->srow_x[2] << " " << header->srow_x[3];
EncapsulateMetaData<std::string>(thisDic, "srow_x", srow_x.str());
std::ostringstream srow_y;
srow_y << header->srow_y[0] << " " << header->srow_y[1] << " " << header->srow_y[2] << " " << header->srow_y[3];
EncapsulateMetaData<std::string>(thisDic, "srow_y", srow_y.str());
std::ostringstream srow_z;
srow_z << header->srow_z[0] << " " << header->srow_z[1] << " " << header->srow_z[2] << " " << header->srow_z[3];
EncapsulateMetaData<std::string>(thisDic, "srow_z", srow_z.str());
std::ostringstream intent_name;
intent_name << header->intent_name;
EncapsulateMetaData<std::string>(thisDic, "intent_name", intent_name.str());
free(header);
}
}
void
NiftiImageIO
::ReadImageInformation()
{
this->m_NiftiImage=nifti_image_read(this->GetFileName(),false);
static std::string prev;
if(prev != this->GetFileName())
{
#if defined(__USE_VERY_VERBOSE_NIFTI_DEBUGGING__)
DumpNiftiHeader(this->GetFileName());
#endif
prev = this->GetFileName();
}
if(this->m_NiftiImage == 0)
{
itkExceptionMacro(<< this->GetFileName() << " is not recognized as a NIFTI file");
}
//Check the intent code, it is a vector image, or matrix image, then this is not true.
//
if(this->m_NiftiImage->intent_code == NIFTI_INTENT_VECTOR ||
this->m_NiftiImage->intent_code == NIFTI_INTENT_SYMMATRIX)
{
if(this->m_NiftiImage->dim[4] > 1)
{
this->SetNumberOfDimensions(4);
}
else if(this->m_NiftiImage->dim[3] > 1)
{
this->SetNumberOfDimensions(3);
}
else if(this->m_NiftiImage->dim[2] > 1)
{
this->SetNumberOfDimensions(2);
}
else
{
this->SetNumberOfDimensions(1);
}
}
else if(this->m_NiftiImage->intent_code == NIFTI_INTENT_GENMATRIX)
{ //TODO: NEED TO DEAL WITH CASE WHERE NIFTI_INTENT_MATRIX
itkExceptionMacro(<< this->GetFileName() << " has an intent code of NIFTI_INTENT_GENMATRIX which is not yet implemented in ITK");
}
else
{ //Simple Scalar Image
//
// this->SetNumberOfDimensions(this->m_NiftiImage->dim[0]);
// HACK ALERT KW
// Apparently some straight-from-the-scanner files report as 4D
// with T = 1; this causes ImageFileReader to erroneously ignore the reported
// direction cosines.
unsigned realdim;
for(realdim = this->m_NiftiImage->dim[0];
this->m_NiftiImage->dim[realdim] == 1 && realdim > 3;
realdim--)
{
}
this->SetNumberOfDimensions(realdim);
this->SetNumberOfComponents(1);
}
if(this->m_NiftiImage->intent_code == NIFTI_INTENT_VECTOR ||
this->m_NiftiImage->intent_code == NIFTI_INTENT_SYMMATRIX)
{
this->SetNumberOfComponents(this->m_NiftiImage->dim[5]);
}
else if(this->m_NiftiImage->intent_code == NIFTI_INTENT_GENMATRIX)
{ //TODO: NEED TO DEAL WITH CASE WHERE NIFTI_INTENT_MATRIX
itkExceptionMacro(<< this->GetFileName() << " has an intent code of NIFTI_INTENT_GENMATRIX which is not yet implemented in ITK");
}
//TODO: Dealing with NIFTI_INTENT_VECTOR or NIFTI_INTENT_GENMATRIX with data type of NIFTI_TYPE_COMPLEX64 NIFTI_TYPE_COMPLEX128 NIFTI_TYPE_RGB24 not supported.
switch( this->m_NiftiImage->datatype )
{
case NIFTI_TYPE_INT8:
this->m_ComponentType = CHAR;
this->m_PixelType = SCALAR;
break;
case NIFTI_TYPE_UINT8:
this->m_ComponentType = UCHAR;
this->m_PixelType = SCALAR;
break;
case NIFTI_TYPE_INT16:
this->m_ComponentType = SHORT;
this->m_PixelType = SCALAR;
break;
case NIFTI_TYPE_UINT16:
this->m_ComponentType = USHORT;
this->m_PixelType = SCALAR;
break;
case NIFTI_TYPE_INT32:
this->m_ComponentType = INT;
this->m_PixelType = SCALAR;
break;
case NIFTI_TYPE_UINT32:
this->m_ComponentType = UINT;
this->m_PixelType = SCALAR;
break;
case NIFTI_TYPE_FLOAT32:
this->m_ComponentType = FLOAT;
this->m_PixelType = SCALAR;
break;
case NIFTI_TYPE_FLOAT64:
this->m_ComponentType = DOUBLE;
this->m_PixelType = SCALAR;
break;
case NIFTI_TYPE_COMPLEX64:
this->m_ComponentType = FLOAT;
this->m_PixelType = COMPLEX;
this->SetNumberOfComponents(2);
break;
case NIFTI_TYPE_COMPLEX128:
this->m_ComponentType = DOUBLE;
this->m_PixelType = COMPLEX;
this->SetNumberOfComponents(2);
break;
case NIFTI_TYPE_RGB24:
this->m_ComponentType = UCHAR;
this->m_PixelType = RGB;
this->SetNumberOfComponents(3);
//TODO: Need to be able to read/write RGB images into ITK.
// case DT_RGB:
// DEBUG -- Assuming this is a triple, not quad
//image.setDataType( uiig::DATA_RGBQUAD );
break;
case NIFTI_TYPE_RGBA32:
this->m_ComponentType = UCHAR;
this->m_PixelType = RGBA;
this->SetNumberOfComponents(4);
break;
default:
break;
}
// there are a wide variety of intents we ignore
// but a few wee need to care about
switch(this->m_NiftiImage->intent_code)
{
case NIFTI_INTENT_NONE:
break;
case NIFTI_INTENT_CORREL:
break;
case NIFTI_INTENT_TTEST:
break;
case NIFTI_INTENT_FTEST:
break;
case NIFTI_INTENT_ZSCORE:
break;
case NIFTI_INTENT_CHISQ:
break;
case NIFTI_INTENT_BETA:
break;
case NIFTI_INTENT_BINOM:
break;
case NIFTI_INTENT_GAMMA:
break;
case NIFTI_INTENT_POISSON:
break;
case NIFTI_INTENT_NORMAL:
break;
case NIFTI_INTENT_FTEST_NONC:
break;
case NIFTI_INTENT_CHISQ_NONC:
break;
case NIFTI_INTENT_LOGISTIC:
break;
case NIFTI_INTENT_LAPLACE:
break;
case NIFTI_INTENT_UNIFORM:
break;
case NIFTI_INTENT_TTEST_NONC:
break;
case NIFTI_INTENT_WEIBULL:
break;
case NIFTI_INTENT_CHI:
break;
case NIFTI_INTENT_INVGAUSS:
break;
case NIFTI_INTENT_EXTVAL:
break;
case NIFTI_INTENT_PVAL:
break;
case NIFTI_INTENT_LOGPVAL:
break;
case NIFTI_INTENT_LOG10PVAL:
break;
case NIFTI_INTENT_ESTIMATE:
break;
case NIFTI_INTENT_LABEL:
break;
case NIFTI_INTENT_NEURONAME:
break;
case NIFTI_INTENT_GENMATRIX:
break;
case NIFTI_INTENT_SYMMATRIX:
this->SetPixelType(SYMMETRICSECONDRANKTENSOR);
break;
case NIFTI_INTENT_DISPVECT:
break;
case NIFTI_INTENT_VECTOR:
this->SetPixelType(VECTOR);
break;
case NIFTI_INTENT_POINTSET:
break;
case NIFTI_INTENT_TRIANGLE:
break;
case NIFTI_INTENT_QUATERNION:
break;
case NIFTI_INTENT_DIMLESS:
break;
case NIFTI_INTENT_TIME_SERIES:
break;
case NIFTI_INTENT_NODE_INDEX:
break;
case NIFTI_INTENT_RGB_VECTOR:
break;
case NIFTI_INTENT_RGBA_VECTOR:
break;
case NIFTI_INTENT_SHAPE:
break;
}
// set slope/intercept
if(this->m_NiftiImage->qform_code == 0
&& this->m_NiftiImage->sform_code == 0)
{
this->m_RescaleSlope = 1;
this->m_RescaleIntercept = 0;
}
else
{
if((this->m_RescaleSlope = this->m_NiftiImage->scl_slope) == 0)
{
this->m_RescaleSlope = 1;
}
this->m_RescaleIntercept = this->m_NiftiImage->scl_inter;
}
this->m_OnDiskComponentType = this->m_ComponentType;
//
// if rescale is necessary, promote type reported
// to ImageFileReader to float
if(this->MustRescale())
{
if(this->m_ComponentType == CHAR ||
this->m_ComponentType == UCHAR ||
this->m_ComponentType == SHORT ||
this->m_ComponentType == USHORT ||
this->m_ComponentType == INT ||
this->m_ComponentType == UINT ||
this->m_ComponentType == LONG ||
this->m_ComponentType == ULONG)
{
this->m_ComponentType = FLOAT;
}
}
//
// set up the dimension stuff
double spacingscale=1.0;//default to mm
switch(XYZT_TO_SPACE(this->m_NiftiImage->xyz_units))
{
case NIFTI_UNITS_METER:
spacingscale=1e3;
break;
case NIFTI_UNITS_MM:
spacingscale=1e0;
break;
case NIFTI_UNITS_MICRON:
spacingscale=1e-3;
break;
}
double timingscale=1.0;//Default to seconds
switch(XYZT_TO_TIME(this->m_NiftiImage->xyz_units))
{
case NIFTI_UNITS_SEC:
timingscale=1.0;
break;
case NIFTI_UNITS_MSEC:
timingscale=1e-3;
break;
case NIFTI_UNITS_USEC:
timingscale=1e-6;
break;
}
const int dims=this->GetNumberOfDimensions();
switch(dims)
{
case 7:
this->SetDimensions(6,this->m_NiftiImage->nw);
//NOTE: Scaling is not defined in this dimension
this->SetSpacing(6,this->m_NiftiImage->dw);
case 6:
this->SetDimensions(5,this->m_NiftiImage->nv);
//NOTE: Scaling is not defined in this dimension
this->SetSpacing(5,this->m_NiftiImage->dv);
case 5:
this->SetDimensions(4,this->m_NiftiImage->nu);
//NOTE: Scaling is not defined in this dimension
this->SetSpacing(4,this->m_NiftiImage->du);
case 4:
this->SetDimensions(3,this->m_NiftiImage->nt);
this->SetSpacing(3,this->m_NiftiImage->dt*timingscale);
case 3:
this->SetDimensions(2,this->m_NiftiImage->nz);
this->SetSpacing(2,this->m_NiftiImage->dz*spacingscale);
case 2:
this->SetDimensions(1,this->m_NiftiImage->ny);
this->SetSpacing(1,this->m_NiftiImage->dy*spacingscale);
case 1:
this->SetDimensions(0,this->m_NiftiImage->nx);
this->SetSpacing(0,this->m_NiftiImage->dx*spacingscale);
}
this->ComputeStrides();
//Get Dictionary Information
//Insert Orientation.
//Need to encapsulate as much Nifti information as possible here.
MetaDataDictionary &thisDic=this->GetMetaDataDictionary();
std::string classname(this->GetNameOfClass());
EncapsulateMetaData<std::string>(thisDic,ITK_InputFilterName, classname);
switch(this->m_ComponentType)
{
case CHAR:
EncapsulateMetaData<std::string>(thisDic,ITK_OnDiskStorageTypeName,
std::string(typeid(char).name()));
break;
case UCHAR:
if(this->m_PixelType == RGB)
{
EncapsulateMetaData<std::string>(thisDic,ITK_OnDiskStorageTypeName,
std::string("RGB"));
}
else if(this->m_PixelType == RGBA)
{
EncapsulateMetaData<std::string>(thisDic,ITK_OnDiskStorageTypeName,
std::string("RGBA"));
}
else
{
EncapsulateMetaData<std::string>(thisDic,ITK_OnDiskStorageTypeName,
std::string(typeid(unsigned char).name()));
}
break;
case SHORT:
EncapsulateMetaData<std::string>(thisDic,ITK_OnDiskStorageTypeName,
std::string(typeid(short).name()));
break;
case USHORT:
EncapsulateMetaData<std::string>(thisDic,ITK_OnDiskStorageTypeName,
std::string(typeid(unsigned short).name()));
break;
case INT:
EncapsulateMetaData<std::string>(thisDic,ITK_OnDiskStorageTypeName,
std::string(typeid(long).name()));
break;
case UINT:
EncapsulateMetaData<std::string>(thisDic,ITK_OnDiskStorageTypeName,
std::string(typeid(unsigned long).name()));
break;
case FLOAT:
EncapsulateMetaData<std::string>(thisDic,ITK_OnDiskStorageTypeName,
std::string(typeid(float).name()));
break;
case DOUBLE:
EncapsulateMetaData<std::string>(thisDic,ITK_OnDiskStorageTypeName,
std::string(typeid(double).name()));
break;
// case NIFTI_TYPE_RGB24: handled above under UChar
// case DT_RGB:
// DEBUG -- Assuming this is a triple, not quad
//image.setDataType( uiig::DATA_RGBQUAD );
// break;
default:
break;
}
// set the image orientation
this->SetImageIOOrientationFromNIfTI(dims);
// Set the metadata.
this->SetImageIOMetadataFromNIfTI();
//Important hist fields
std::string description(this->m_NiftiImage->descrip);
EncapsulateMetaData<std::string>(this->GetMetaDataDictionary(),
ITK_FileNotes,description);
// We don't need the image anymore
nifti_image_free(this->m_NiftiImage);
this->m_NiftiImage = 0;
}
namespace
{
inline mat44 mat44_transpose(mat44 in)
{
mat44 out;
for(unsigned int i = 0; i < 4; i++)
{
for(unsigned int j = 0; j < 4; j++)
{
out.m[i][j] = in.m[j][i];
}
}
return out;
}
}
/**
* For Nifti this does not write a file, it only fills in the
* appropriate header information.
*/
void
NiftiImageIO
::WriteImageInformation(void)
{
// MetaDataDictionary &thisDic=this->GetMetaDataDictionary();
//
//
// First of all we need to not go any further if there's
// a dimension of the image that won't fit in a 16 bit short.
for(unsigned int i = 0; i < this->GetNumberOfDimensions(); i++)
{
unsigned int curdim(this->GetDimensions(i));
if(curdim > static_cast<unsigned int>(NumericTraits<short>::max()))
{
itkExceptionMacro( << "Dimension(" << i << ") = " << curdim
<< " is greater than maximum possible dimension "
<< NumericTraits<short>::max() );
}
}
// fill out the image header.
if(this->m_NiftiImage == 0)
{
this->m_NiftiImage = nifti_simple_init_nim();
}
//
// set the filename
std::string FName(this->GetFileName());
//
// set the file type
const char * tempextension=nifti_find_file_extension(FName.c_str());
if(tempextension == NULL)
{
itkExceptionMacro( <<
"Bad Nifti file name. No extension found for file: " << FName);
}
const std::string ExtensionName( tempextension );
char *tempbasename=nifti_makebasename(FName.c_str());
const std::string BaseName(tempbasename);
free(tempbasename); //Need to clear the extension
const std::string::size_type ext = ExtensionName.rfind(".gz");
const bool IsCompressed=(ext == std::string::npos)?false:true;
if( ( ExtensionName == ".nii" || ExtensionName == ".nii.gz" ) &&
this->GetUseLegacyModeForTwoFileWriting() == false)
{
this->m_NiftiImage->nifti_type = NIFTI_FTYPE_NIFTI1_1;
}
else if ( (ExtensionName == ".nia" ) &&
this->GetUseLegacyModeForTwoFileWriting() == false)
{
this->m_NiftiImage->nifti_type = NIFTI_FTYPE_ASCII;
}
else if(ExtensionName == ".hdr" || ExtensionName == ".img"
|| ExtensionName == ".hdr.gz" || ExtensionName == ".img.gz" )
{ //NOTE: LegacyMode is only valid for header extensions .hdr and .img
if(this->GetUseLegacyModeForTwoFileWriting() == false)
{
// This filter needs to write nifti files in it's default mode
// , not default to legacy analyze files.
this->m_NiftiImage->nifti_type = NIFTI_FTYPE_NIFTI1_2;
}
else
{
// If it is desired to write out the nifti variant of
// ANALYZE7.5.
// NOTE: OREINTATION IS NOT WELL DEFINED IN THIS FORMAT.
this->m_NiftiImage->nifti_type = NIFTI_FTYPE_ANALYZE;
}
}
else
{
itkExceptionMacro(<< "Bad Nifti file name: " << FName);
}
this->m_NiftiImage->fname = nifti_makehdrname(BaseName.c_str(),this->m_NiftiImage->nifti_type,false,IsCompressed);
this->m_NiftiImage->iname = nifti_makeimgname(BaseName.c_str(),this->m_NiftiImage->nifti_type,false,IsCompressed);
// FIELD NOTES
// -----------------------------------------------------
// sizeof_hdr must be 348
// -----------------------------------------------------
// dim dim[0] and dim[1] are always required;
// dim[2] is required for 2-D volumes,
// dim[3] for 3-D volumes, etc.
this->m_NiftiImage->nvox = 1;
//Spacial dims in ITK are given in mm.
//If 4D assume 4thD is in SECONDS, for all of ITK.
//NOTE: Due to an ambiguity in the nifti specification, some developers
// external tools believe that the time units must be set, even if there
// is only one dataset. Having the time specified for a purly spatial
// image has no consequence, so go ahead and set it to seconds.
this->m_NiftiImage->xyz_units= static_cast< int >( NIFTI_UNITS_MM | NIFTI_UNITS_SEC );
this->m_NiftiImage->dim[7] = this->m_NiftiImage->nw=1;
this->m_NiftiImage->dim[6] = this->m_NiftiImage->nv=1;
this->m_NiftiImage->dim[5] = this->m_NiftiImage->nu=1;
this->m_NiftiImage->dim[4] = this->m_NiftiImage->nt=1;
this->m_NiftiImage->dim[3] = this->m_NiftiImage->nz=1;
this->m_NiftiImage->dim[2] = this->m_NiftiImage->ny=1;
this->m_NiftiImage->dim[1] = this->m_NiftiImage->nx=1;
switch(this->GetNumberOfDimensions())
{
case 7:
this->m_NiftiImage->dim[7] = this->m_NiftiImage->nw
= static_cast< int >( this->GetDimensions(6) );
this->m_NiftiImage->pixdim[7] = this->m_NiftiImage->dw =
static_cast<float>( this->GetSpacing(6) );
this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[7];
case 6:
this->m_NiftiImage->dim[6] = this->m_NiftiImage->nv
= this->GetDimensions(5);
this->m_NiftiImage->pixdim[6] = this->m_NiftiImage->dv =
static_cast<float>( this->GetSpacing(5) );
this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[6];
case 5:
this->m_NiftiImage->dim[5] =
this->m_NiftiImage->nu = this->GetDimensions(4);
this->m_NiftiImage->pixdim[5] =
this->m_NiftiImage->du = static_cast<float>( this->GetSpacing(4) );
this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[5];
case 4:
this->m_NiftiImage->dim[4] = this->m_NiftiImage->nt
= this->GetDimensions(3);
this->m_NiftiImage->pixdim[4] =
this->m_NiftiImage->dt = static_cast<float>( this->GetSpacing(3) );
this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[4];
case 3:
this->m_NiftiImage->dim[3] = this->m_NiftiImage->nz
= this->GetDimensions(2);
this->m_NiftiImage->pixdim[3] =
this->m_NiftiImage->dz = static_cast<float>( this->GetSpacing(2) );
this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[3];
case 2:
this->m_NiftiImage->dim[2] = this->m_NiftiImage->ny
= this->GetDimensions(1);
this->m_NiftiImage->pixdim[2] =
this->m_NiftiImage->dy = static_cast<float>( this->GetSpacing(1) );
this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[2];
case 1:
this->m_NiftiImage->dim[1] = this->m_NiftiImage->nx
= this->GetDimensions(0);
this->m_NiftiImage->pixdim[1] =
this->m_NiftiImage->dx = static_cast<float>( this->GetSpacing(0) );
this->m_NiftiImage->nvox *= this->m_NiftiImage->dim[1];
}
const unsigned int numComponents = this->GetNumberOfComponents();
//TODO: Also need to check for RGB images where numComponets=3
if( numComponents > 1
&& !(this->GetPixelType() == COMPLEX
&& numComponents == 2)
&& !(this->GetPixelType() == RGB
&& numComponents == 3)
&& !(this->GetPixelType() == RGBA
&& numComponents == 4))
{
this->m_NiftiImage->ndim = 5; //This must be 5 for NIFTI_INTENT_VECTOR images.
this->m_NiftiImage->dim[0] = 5; //This must be 5 for NIFTI_INTENT_VECTOR images.
if(this->GetNumberOfDimensions()> 4)
{
itkExceptionMacro(<< "Can not store a vector image of more than 4 dimensions in a Nifti file. Dimension=" << this->GetNumberOfDimensions() );
}
//
// support symmetric matrix type
if(this->GetPixelType() == ImageIOBase::DIFFUSIONTENSOR3D ||
this->GetPixelType() == ImageIOBase::SYMMETRICSECONDRANKTENSOR)
{
this->m_NiftiImage->intent_code = NIFTI_INTENT_SYMMATRIX;
}
else
{
this->m_NiftiImage->intent_code = NIFTI_INTENT_VECTOR;
}
this->m_NiftiImage->nu =
this->m_NiftiImage->dim[5] = this->GetNumberOfComponents();
if(this->GetNumberOfDimensions() < 4)
{
this->m_NiftiImage->nt =
this->m_NiftiImage->dim[4] = 1;
}
if(this->GetNumberOfDimensions() < 3)
{
this->m_NiftiImage->nz =
this->m_NiftiImage->dim[3] = 1;
}
if(this->GetNumberOfDimensions() < 2)
{
this->m_NiftiImage->ny =
this->m_NiftiImage->dim[2] = 1;
}
if(this->GetNumberOfDimensions() < 1)
{
this->m_NiftiImage->nx =
this->m_NiftiImage->dim[1] = 1;
}
// Update nvox value because in nifti, vector components are the slowest changing direction, not the fastest.
this->m_NiftiImage->nvox *= this->GetNumberOfComponents();
}
else
{
this->m_NiftiImage->ndim = this->GetNumberOfDimensions();
this->m_NiftiImage->dim[0] = this->GetNumberOfDimensions();
}
// -----------------------------------------------------
// datatype needed to specify type of image data
// -----------------------------------------------------
// bitpix should correspond correctly to datatype
// -----------------------------------------------------
switch(this->GetComponentType())
{
case UCHAR:
this->m_NiftiImage->datatype = NIFTI_TYPE_UINT8;
this->m_NiftiImage->nbyper = 1;
break;
case CHAR:
this->m_NiftiImage->datatype = NIFTI_TYPE_INT8;
this->m_NiftiImage->nbyper = 1;
break;
case USHORT:
this->m_NiftiImage->datatype = NIFTI_TYPE_UINT16;
this->m_NiftiImage->nbyper = 2;
break;
case SHORT:
this->m_NiftiImage->datatype = NIFTI_TYPE_INT16;
this->m_NiftiImage->nbyper = 2;
break;
case ULONG:
case UINT:
this->m_NiftiImage->datatype = NIFTI_TYPE_UINT32;
this->m_NiftiImage->nbyper = 4;
break;
case LONG:
case INT:
this->m_NiftiImage->datatype = NIFTI_TYPE_INT32;
this->m_NiftiImage->nbyper = 4;
break;
case FLOAT:
this->m_NiftiImage->datatype = NIFTI_TYPE_FLOAT32;
this->m_NiftiImage->nbyper = 4;
break;
case DOUBLE:
this->m_NiftiImage->datatype = NIFTI_TYPE_FLOAT64;
this->m_NiftiImage->nbyper = 8;
break;
case UNKNOWNCOMPONENTTYPE:
default:
{
itkExceptionMacro(<<
"More than one component per pixel not supported");
}
}
switch(this->GetPixelType())
{
case VECTOR: //NOTE: VECTOR is un-rolled by nifti to look like a multi-dimensional scalar image
case SCALAR:
break;
case RGB:
this->m_NiftiImage->nbyper *= 3;
this->m_NiftiImage->datatype = NIFTI_TYPE_RGB24;
break;
case RGBA:
this->m_NiftiImage->nbyper *= 4;
this->m_NiftiImage->datatype = NIFTI_TYPE_RGBA32;
break;
case COMPLEX:
this->m_NiftiImage->nbyper *= 2;
switch(this->GetComponentType())
{
case FLOAT:
this->m_NiftiImage->datatype = NIFTI_TYPE_COMPLEX64;
break;
case DOUBLE:
this->m_NiftiImage->datatype = NIFTI_TYPE_COMPLEX128;
break;
default:
{
itkExceptionMacro(<<
"Only float or double precision complex type supported");
}
}
break;
case SYMMETRICSECONDRANKTENSOR:
case DIFFUSIONTENSOR3D:
break;
case OFFSET:
case POINT:
case COVARIANTVECTOR:
case FIXEDARRAY:
case MATRIX:
case UNKNOWNPIXELTYPE:
default:
itkExceptionMacro(<<
"Can not process this pixel type for writing into nifti");
break;
}
// -----------------------------------------------------
// vox_offset required for an "n+1" header
// -----------------------------------------------------
// magic must be "ni1\0" or "n+1\0"
// -----------------------------------------------------
this->m_NiftiImage->scl_slope = 1.0f;
this->m_NiftiImage->scl_inter = 0.0f;
this->SetNIfTIOrientationFromImageIO(this->GetNumberOfDimensions(),this->GetNumberOfDimensions()); //TODO: Note both arguments are the same, no need to distinguish between them.
return;
}
namespace
{
void Normalize(std::vector<double> &x)
{
double sum = 0;
for(unsigned int i = 0; i < x.size(); i++)
{
sum += (x[i] * x[i]);
}
if(sum == 0.0)
{
return;
}
sum = vcl_sqrt(sum);
for(unsigned int i = 0; i < x.size(); i++)
{
x[i] = x[i] / sum;
}
}
}
void
NiftiImageIO::
SetImageIOOrientationFromNIfTI(unsigned short int dims)
{
typedef SpatialOrientationAdapter OrientAdapterType;
//
// in the case of an Analyze75 file, use old analyze orient method.
if(this->m_NiftiImage->qform_code == 0
&& this->m_NiftiImage->sform_code == 0)
{
SpatialOrientationAdapter::DirectionType dir;
SpatialOrientationAdapter::OrientationType orient;
switch(this->m_NiftiImage->analyze75_orient)
{
case a75_transverse_unflipped:
orient = SpatialOrientation::ITK_COORDINATE_ORIENTATION_RPI;
break;
case a75_sagittal_unflipped:
orient = SpatialOrientation::ITK_COORDINATE_ORIENTATION_PIR;
break;
// according to analyze documents, you don't see flipped
// orientation in the wild
case a75_transverse_flipped:
case a75_coronal_flipped:
case a75_sagittal_flipped:
case a75_orient_unknown:
case a75_coronal_unflipped:
orient = SpatialOrientation::ITK_COORDINATE_ORIENTATION_RIP;
break;
}
dir = OrientAdapterType().ToDirectionCosines(orient);
m_Origin[0] = m_Origin[1] = 0;
if(dims > 2)
{
m_Origin[2] = 0;
}
return;
}
// not an Analyze file.
// scale image data based on slope/intercept
//
// qform or sform
//
mat44 theMat;
if(this->m_NiftiImage->qform_code > 0)
{
theMat = this->m_NiftiImage->qto_xyz;
}
// else if(this->m_NiftiImage->sform_code > 0)
else
{
theMat = this->m_NiftiImage->sto_xyz;
}
//
// set origin
m_Origin[0] = -theMat.m[0][3];
if(dims > 1)
{
m_Origin[1] = -theMat.m[1][3];
}
if(dims > 2)
{
m_Origin[2] = theMat.m[2][3];
}
const int max_defined_orientation_dims=(dims > 3)?3:dims;
std::vector<double> xDirection(dims,0);
for (int i = 0; i < max_defined_orientation_dims; i++)
{
xDirection[i] = theMat.m[i][0];
if(i < 2)
{
xDirection[i] *= -1.0;
}
}
Normalize(xDirection);
this->SetDirection(0,xDirection);
if(max_defined_orientation_dims > 1 )
{
std::vector<double> yDirection(dims,0);
for (int i = 0; i < max_defined_orientation_dims; i++)
{
yDirection[i] = theMat.m[i][1];
if(i < 2)
{
yDirection[i] *= -1.0;
}
}
Normalize(yDirection);
this->SetDirection(1,yDirection);
}
if(max_defined_orientation_dims > 2 )
{
std::vector<double> zDirection(dims,0);
for (int i = 0; i < max_defined_orientation_dims; i++)
{
zDirection[i] = theMat.m[i][2];
if(i < 2)
{
zDirection[i] *= -1.0;
}
}
Normalize(zDirection);
this->SetDirection(2,zDirection);
}
}
void
NiftiImageIO::
SetNIfTIOrientationFromImageIO(unsigned short int origdims, unsigned short int dims)
{
//
// use NIFTI method 2
this->m_NiftiImage->sform_code = NIFTI_XFORM_SCANNER_ANAT;
this->m_NiftiImage->qform_code = NIFTI_XFORM_ALIGNED_ANAT;
//
// set the quarternions, from the direction vectors
//Initialize to size 3 with values of 0
//
//The type here must be float, because that matches the signature
//of the nifti_make_orthog_mat44() method below.
typedef float DirectionMatrixComponentType;
int mindims(dims < 3 ? 3 : dims);
std::vector<DirectionMatrixComponentType> dirx(mindims,0);
unsigned int i;
for(i=0; i < this->GetDirection(0).size(); i++)
{
dirx[i] = static_cast<DirectionMatrixComponentType>(-this->GetDirection(0)[i]);
}
if(i < 3)
{
dirx[2] = 0.0f;
}
std::vector<DirectionMatrixComponentType> diry(mindims,0);
if(origdims > 1)
{
for(i=0; i < this->GetDirection(1).size(); i++)
{
diry[i] = static_cast<DirectionMatrixComponentType>(-this->GetDirection(1)[i]);
}
if(i < 3)
{
diry[2] = 0.0f;
}
}
std::vector<DirectionMatrixComponentType> dirz(mindims,0);
if(origdims > 2)
{
for(unsigned int ii=0; ii < this->GetDirection(2).size(); ii++)
{
dirz[ii] = static_cast<DirectionMatrixComponentType>( -this->GetDirection(2)[ii] );
}
// Read comments in nifti1.h about interpreting
// "DICOM Image Orientation (Patient)"
dirx[2] = - dirx[2];
diry[2] = - diry[2];
dirz[2] = - dirz[2];
}
else
{
dirz[0] = dirz[1] = 0.0f;
dirz[2] = 1.0f;
}
mat44 matrix =
nifti_make_orthog_mat44(dirx[0],dirx[1],dirx[2],
diry[0],diry[1],diry[2],
dirz[0],dirz[1],dirz[2]);
matrix = mat44_transpose(matrix);
// Fill in origin.
matrix.m[0][3]= static_cast<float>(-this->GetOrigin(0));
matrix.m[1][3] = (origdims > 1) ? static_cast<float>(-this->GetOrigin(1)) : 0.0f;
//NOTE: The final dimension is not negated!
matrix.m[2][3] = (origdims > 2) ? static_cast<float>(this->GetOrigin(2)) : 0.0f;
nifti_mat44_to_quatern(matrix,
&(this->m_NiftiImage->quatern_b),
&(this->m_NiftiImage->quatern_c),
&(this->m_NiftiImage->quatern_d),
&(this->m_NiftiImage->qoffset_x),
&(this->m_NiftiImage->qoffset_y),
&(this->m_NiftiImage->qoffset_z),
0,
0,
0,
&(this->m_NiftiImage->qfac));
// copy q matrix to s matrix
this->m_NiftiImage->qto_xyz = matrix;
this->m_NiftiImage->sto_xyz = matrix;
//
//
unsigned int sto_limit = origdims > 3 ? 3 : origdims;
for(unsigned int ii = 0; ii < sto_limit; ii++)
{
for(unsigned int jj = 0; jj < sto_limit; jj++)
{
this->m_NiftiImage->sto_xyz.m[ii][jj] =
static_cast<float>( this->GetSpacing(jj) ) *
this->m_NiftiImage->sto_xyz.m[ii][jj];
#if 0 // this is almost certainly wrong and gets overwritten immediately
// below...
this->m_NiftiImage->sto_ijk.m[ii][jj] =
this->m_NiftiImage->sto_xyz.m[ii][jj] / this->GetSpacing(jj);
#endif
}
}
this->m_NiftiImage->sto_ijk =
nifti_mat44_inverse(this->m_NiftiImage->sto_xyz);
this->m_NiftiImage->qto_ijk =
nifti_mat44_inverse(this->m_NiftiImage->qto_xyz);
this->m_NiftiImage->pixdim[0] = this->m_NiftiImage->qfac;
// this->m_NiftiImage->sform_code = 0;
}
/**
* Write the image Information before writing data
*/
void
NiftiImageIO
::Write( const void* buffer)
{
this->WriteImageInformation();
unsigned int numComponents = this->GetNumberOfComponents();
if(numComponents == 1 ||
(numComponents == 2 && this->GetPixelType() == COMPLEX) ||
(numComponents == 3 && this->GetPixelType() == RGB) ||
(numComponents == 4 && this->GetPixelType() == RGBA))
{
// Need a const cast here so that we don't have to copy the memory
// for writing.
this->m_NiftiImage->data=const_cast<void *>(buffer);
nifti_image_write(this->m_NiftiImage);
this->m_NiftiImage->data = 0; // if left pointing to data buffer
// nifti_image_free will try and free this memory
}
else ///Image intent is vector image
{
for(unsigned int i = 1; i < 8; i++)
{
if(this->m_NiftiImage->dim[i] == 0)
{
this->m_NiftiImage->dim[i] = 1;
}
}
const unsigned numVoxels =
this->m_NiftiImage->dim[1] *
this->m_NiftiImage->dim[2] *
this->m_NiftiImage->dim[3] *
this->m_NiftiImage->dim[4];
const unsigned buffer_size =
numVoxels*
numComponents * //Number of componenets
this->m_NiftiImage->nbyper;
char *nifti_buf = new char[buffer_size];
const char * const itkbuf = (const char *)buffer;
// Data must be rearranged to meet nifti organzation.
// nifti_layout[vec][t][z][y][x] = itk_layout[t][z][y][z][vec]
const unsigned int rowdist=m_NiftiImage->dim[1];
const unsigned int slicedist=rowdist*m_NiftiImage->dim[2];
const unsigned int volumedist=slicedist*m_NiftiImage->dim[3];
const unsigned int seriesdist=volumedist*m_NiftiImage->dim[4];
//
// as per ITK bug 0007485
// NIfTI is lower triangular, ITK is upper triangular.
// i.e. if a symmetric matrix is
// a b c
// b d e
// c e f
// ITK stores it a b c d e f, but NIfTI is a b d c e f
// so on read, step sequentially through the source vector, but
// reverse the order of vec[2] and vec[3]
int *vecOrder;
if(this->GetPixelType() == ImageIOBase::DIFFUSIONTENSOR3D ||
this->GetPixelType() == ImageIOBase::SYMMETRICSECONDRANKTENSOR)
{
vecOrder = UpperToLowerOrder(SymMatDim(numComponents));
}
else
{
vecOrder = new int[numComponents];
for(unsigned i = 0; i < numComponents; i++)
{
vecOrder[i] = i;
}
}
for(int t = 0; t < this->m_NiftiImage->dim[4]; t++)
{
for(int z = 0; z < this->m_NiftiImage->dim[3]; z++)
{
for(int y = 0; y < this->m_NiftiImage->dim[2]; y++)
{
for(int x = 0; x < this->m_NiftiImage->dim[1]; x++)
{
for(unsigned int c=0;c< numComponents; c++)
{
const unsigned int nifti_index=(c*seriesdist+volumedist*t + slicedist*z + rowdist*y + x)*this->m_NiftiImage->nbyper;
const unsigned int itk_index=((volumedist*t + slicedist*z + rowdist*y + x)*numComponents + vecOrder[c])*this->m_NiftiImage->nbyper;
memcpy(nifti_buf+nifti_index,itkbuf+itk_index,this->m_NiftiImage->nbyper);
}
}
}
}
}
delete [] vecOrder;
dumpdata(buffer);
dumpdata(tobuffer);
//Need a const cast here so that we don't have to copy the memory for
//writing.
this->m_NiftiImage->data=(void *)nifti_buf;
nifti_image_write(this->m_NiftiImage);
this->m_NiftiImage->data = 0; // if left pointing to data buffer
delete [] nifti_buf;
}
}
} // end namespace itk
|