/usr/lib/python2.7/dist-packages/tifffile.py is in python-tifffile 20170929-1ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 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 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
# tifffile.py
# Copyright (c) 2008-2017, Christoph Gohlke
# Copyright (c) 2008-2017, The Regents of the University of California
# Produced at the Laboratory for Fluorescence Dynamics
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holders nor the names of any
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Read image and meta data from (bio) TIFF® files. Save numpy arrays as TIFF.
Image and metadata can be read from TIFF, BigTIFF, OME-TIFF, STK, LSM, NIH,
SGI, ImageJ, MicroManager, FluoView, SEQ and GEL files.
Tifffile is not a general purpose TIFF library. Only a subset of the TIFF
specification is supported, mainly uncompressed and losslessly compressed
2**(0 to 6) bit integer, 16, 32 and 64-bit float, grayscale and RGB(A) images,
which are commonly used in bio-scientific imaging. Specifically, reading image
trees defined via SubIFDs, JPEG and CCITT compression, chroma subsampling,
or IPTC and XMP metadata are not implemented.
TIFF®, the tagged Image File Format, is a trademark and under control of
Adobe Systems Incorporated. BigTIFF allows for files greater than 4 GB.
STK, LSM, FluoView, SGI, SEQ, GEL, and OME-TIFF, are custom extensions
defined by Molecular Devices (Universal Imaging Corporation), Carl Zeiss
MicroImaging, Olympus, Silicon Graphics International, Media Cybernetics,
Molecular Dynamics, and the Open Microscopy Environment consortium
respectively.
For command line usage run C{python -m tifffile --help}
:Author:
`Christoph Gohlke <http://www.lfd.uci.edu/~gohlke/>`_
:Organization:
Laboratory for Fluorescence Dynamics, University of California, Irvine
:Version: 2017.09.29
Requirements
------------
* `CPython 3.6 64-bit <http://www.python.org>`_
* `Numpy 1.13 <http://www.numpy.org>`_
* `Matplotlib 2.0 <http://www.matplotlib.org>`_ (optional for plotting)
* `Tifffile.c 2017.01.10 <http://www.lfd.uci.edu/~gohlke/>`_
(recommended for faster decoding of PackBits and LZW encoded strings)
Revisions
---------
2017.09.29 (tentative)
Many backwards incompatible changes improving speed and resource usage:
Pass 2268 tests.
Add detail argument to __str__ function. Remove info functions.
Fix potential issue correcting offsets of large LSM files with positions.
Remove TiffFile iterator interface; use TiffFile.pages instead.
Do not make tag values available as TiffPage attributes.
Use str (not bytes) type for tag and metadata strings (WIP).
Use documented standard tag and value names (WIP).
Use enums for some documented TIFF tag values.
Remove 'memmap' and 'tmpfile' options; use out='memmap' instead.
Add option to specify output in asarray functions.
Add option to concurrently decode image strips or tiles using threads.
Add TiffPage.asrgb function (WIP).
Do not apply colormap in asarray.
Remove 'colormapped', 'rgbonly', and 'scale_mdgel' options from asarray.
Consolidate metadata in TiffFile _metadata functions.
Remove non-tag metadata properties from TiffPage.
Add function to convert LSM to tiled BIN files.
Align image data in file.
Make TiffPage.dtype a numpy.dtype.
Add 'ndim' and 'size' properties to TiffPage and TiffPageSeries.
Allow imsave to write non-BigTIFF files up to ~4 GB.
Only read one page for shaped series if possible.
Add memmap function to create memory-mapped array stored in TIFF file.
Add option to save empty arrays to TIFF files.
Add option to save truncated TIFF files.
Allow single tile images to be saved contiguously.
Add optional movie mode for files with uniform pages.
Lazy load pages.
Use lightweight TiffFrame for IFDs sharing properties with key TiffPage.
Move module constants to 'TIFF' namespace (speed up module import).
Remove 'fastij' option from TiffFile.
Remove 'pages' parameter from TiffFile.
Remove TIFFfile alias.
Deprecate Python 2.
Require enum34 and futures packages on Python 2.7.
Remove Record class and return all metadata as dict instead.
Add functions to parse STK, MetaSeries, ScanImage, SVS, Pilatus metadata.
Read tags from EXIF and GPS IFDs.
Use pformat for tag and metadata values.
Fix reading some UIC tags (bug fix).
Do not modify input array in imshow (bug fix).
Fix Python implementation of unpack_ints.
2017.05.23
Pass 1961 tests.
Write correct number of sample_format values (bug fix).
Use Adobe deflate code to write ZIP compressed files.
Add option to pass tag values as packed binary data for writing.
Defer tag validation to attribute access.
Use property instead of lazyattr decorator for simple expressions.
2017.03.17
Write IFDs and tag values on word boundaries.
Read ScanImage metadata.
Remove is_rgb and is_indexed attributes from TiffFile.
Create files used by doctests.
2017.01.12
Read Zeiss SEM metadata.
Read OME-TIFF with invalid references to external files.
Rewrite C LZW decoder (5x faster).
Read corrupted LSM files missing EOI code in LZW stream.
2017.01.01
Add option to append images to existing TIFF files.
Read files without pages.
Read S-FEG and Helios NanoLab tags created by FEI software.
Allow saving Color Filter Array (CFA) images.
Add info functions returning more information about TiffFile and TiffPage.
Add option to read specific pages only.
Remove maxpages argument (backwards incompatible).
Remove test_tifffile function.
2016.10.28
Pass 1944 tests.
Improve detection of ImageJ hyperstacks.
Read TVIPS metadata created by EM-MENU (by Marco Oster).
Add option to disable using OME-XML metadata.
Allow non-integer range attributes in modulo tags (by Stuart Berg).
2016.06.21
Do not always memmap contiguous data in page series.
2016.05.13
Add option to specify resolution unit.
Write grayscale images with extra samples when planarconfig is specified.
Do not write RGB color images with 2 samples.
Reorder TiffWriter.save keyword arguments (backwards incompatible).
2016.04.18
Pass 1932 tests.
TiffWriter, imread, and imsave accept open binary file streams.
2016.04.13
Correctly handle reversed fill order in 2 and 4 bps images (bug fix).
Implement reverse_bitorder in C.
2016.03.18
Fix saving additional ImageJ metadata.
2016.02.22
Pass 1920 tests.
Write 8 bytes double tag values using offset if necessary (bug fix).
Add option to disable writing second image description tag.
Detect tags with incorrect counts.
Disable color mapping for LSM.
2015.11.13
Read LSM 6 mosaics.
Add option to specify directory of memory-mapped files.
Add command line options to specify vmin and vmax values for colormapping.
2015.10.06
New helper function to apply colormaps.
Renamed is_palette attributes to is_indexed (backwards incompatible).
Color-mapped samples are now contiguous (backwards incompatible).
Do not color-map ImageJ hyperstacks (backwards incompatible).
Towards supporting Leica SCN.
2015.09.25
Read images with reversed bit order (FillOrder is LSB2MSB).
2015.09.21
Read RGB OME-TIFF.
Warn about malformed OME-XML.
2015.09.16
Detect some corrupted ImageJ metadata.
Better axes labels for 'shaped' files.
Do not create TiffTag for default values.
Chroma subsampling is not supported.
Memory-map data in TiffPageSeries if possible (optional).
2015.08.17
Pass 1906 tests.
Write ImageJ hyperstacks (optional).
Read and write LZMA compressed data.
Specify datetime when saving (optional).
Save tiled and color-mapped images (optional).
Ignore void bytecounts and offsets if possible.
Ignore bogus image_depth tag created by ISS Vista software.
Decode floating point horizontal differencing (not tiled).
Save image data contiguously if possible.
Only read first IFD from ImageJ files if possible.
Read ImageJ 'raw' format (files larger than 4 GB).
TiffPageSeries class for pages with compatible shape and data type.
Try to read incomplete tiles.
Open file dialog if no filename is passed on command line.
Ignore errors when decoding OME-XML.
Rename decoder functions (backwards incompatible).
2014.08.24
TiffWriter class for incremental writing images.
Simplify examples.
2014.08.19
Add memmap function to FileHandle.
Add function to determine if image data in TiffPage is memory-mappable.
Do not close files if multifile_close parameter is False.
2014.08.10
Pass 1730 tests.
Return all extrasamples by default (backwards incompatible).
Read data from series of pages into memory-mapped array (optional).
Squeeze OME dimensions (backwards incompatible).
Workaround missing EOI code in strips.
Support image and tile depth tags (SGI extension).
Better handling of STK/UIC tags (backwards incompatible).
Disable color mapping for STK.
Julian to datetime converter.
TIFF ASCII type may be NULL separated.
Unwrap strip offsets for LSM files greater than 4 GB.
Correct strip byte counts in compressed LSM files.
Skip missing files in OME series.
Read embedded TIFF files.
2014.02.05
Save rational numbers as type 5 (bug fix).
2013.12.20
Keep other files in OME multi-file series closed.
FileHandle class to abstract binary file handle.
Disable color mapping for bad OME-TIFF produced by bio-formats.
Read bad OME-XML produced by ImageJ when cropping.
2013.11.03
Allow zlib compress data in imsave function (optional).
Memory-map contiguous image data (optional).
2013.10.28
Read MicroManager metadata and little endian ImageJ tag.
Save extra tags in imsave function.
Save tags in ascending order by code (bug fix).
2012.10.18
Accept file like objects (read from OIB files).
2012.08.21
Rename TIFFfile to TiffFile and TIFFpage to TiffPage.
TiffSequence class for reading sequence of TIFF files.
Read UltraQuant tags.
Allow float numbers as resolution in imsave function.
2012.08.03
Read MD GEL tags and NIH Image header.
2012.07.25
Read ImageJ tags.
...
Notes
-----
The API is not stable yet and might change between revisions.
Tested on little-endian platforms only.
Other Python packages and modules for reading bio-scientific TIFF files:
* `python-bioformats <https://github.com/CellProfiler/python-bioformats>`_
* `Imread <https://github.com/luispedro/imread>`_
* `PyLibTiff <https://github.com/pearu/pylibtiff>`_
* `SimpleITK <http://www.simpleitk.org>`_
* `PyLSM <https://launchpad.net/pylsm>`_
* `PyMca.TiffIO.py <https://github.com/vasole/pymca>`_ (same as fabio.TiffIO)
* `BioImageXD.Readers <http://www.bioimagexd.net/>`_
* `Cellcognition.io <http://cellcognition.org/>`_
* `pymimage <https://github.com/ardoi/pymimage>`_
Acknowledgements
----------------
* Egor Zindy, University of Manchester, for lsm_scan_info specifics.
* Wim Lewis for a bug fix and some LSM functions.
* Hadrien Mary for help on reading MicroManager files.
* Christian Kliche for help writing tiled and color-mapped files.
References
----------
1) TIFF 6.0 Specification and Supplements. Adobe Systems Incorporated.
http://partners.adobe.com/public/developer/tiff/
2) TIFF File Format FAQ. http://www.awaresystems.be/imaging/tiff/faq.html
3) MetaMorph Stack (STK) Image File Format.
http://support.meta.moleculardevices.com/docs/t10243.pdf
4) Image File Format Description LSM 5/7 Release 6.0 (ZEN 2010).
Carl Zeiss MicroImaging GmbH. BioSciences. May 10, 2011
5) The OME-TIFF format.
http://www.openmicroscopy.org/site/support/file-formats/ome-tiff
6) UltraQuant(r) Version 6.0 for Windows Start-Up Guide.
http://www.ultralum.com/images%20ultralum/pdf/UQStart%20Up%20Guide.pdf
7) Micro-Manager File Formats.
http://www.micro-manager.org/wiki/Micro-Manager_File_Formats
8) Tags for TIFF and Related Specifications. Digital Preservation.
http://www.digitalpreservation.gov/formats/content/tiff_tags.shtml
9) ScanImage BigTiff Specification - ScanImage 2016.
http://scanimage.vidriotechnologies.com/display/SI2016/
ScanImage+BigTiff+Specification
10) CIPA DC-008-2016: Exchangeable image file format for digital still cameras:
Exif Version 2.31.
http://www.cipa.jp/std/documents/e/DC-008-Translation-2016-E.pdf
Examples
--------
>>> # write and read numpy array
>>> data = numpy.random.rand(5, 301, 219)
>>> imsave('temp.tif', data)
>>> image = imread('temp.tif')
>>> numpy.testing.assert_array_equal(image, data)
>>> # iterate over pages and tags
>>> with TiffFile('temp.tif') as tif:
... images = tif.asarray()
... for page in tif.pages:
... for tag in page.tags.values():
... _ = tag.name, tag.value
... image = page.asarray()
"""
from __future__ import division, print_function
import sys
import os
import io
import re
import glob
import math
import zlib
import time
import json
import enum
import struct
import warnings
import tempfile
import datetime
import threading
import collections
import multiprocessing
import concurrent.futures
# from fractions import Fraction # delay import
# from xml.etree import cElementTree as etree # delay import
import numpy
try:
import lzma
except ImportError:
try:
import backports.lzma as lzma
except ImportError:
lzma = None
__version__ = '2017.09.29'
__docformat__ = 'restructuredtext en'
__all__ = (
'imsave', 'imread', 'imshow', 'memmap',
'TiffFile', 'TiffWriter', 'TiffSequence',
# utility functions used by oiffile or czifile
'FileHandle', 'lazyattr', 'natural_sorted', 'decode_lzw', 'stripnull',
'create_output', 'repeat_nd', 'format_size', 'product')
def imread(files, **kwargs):
"""Return image data from TIFF file(s) as numpy array.
Refer to the TiffFile class and member functions for documentation.
Parameters
----------
files : str, binary stream, or sequence
File name, seekable binary stream, glob pattern, or sequence of
file names.
kwargs : dict
Parameters 'multifile' and 'is_ome' are passed to the TiffFile class.
The 'pattern' parameter is passed to the TiffSequence class.
Other parameters are passed to the asarray functions.
The first image series is returned if no arguments are provided.
Examples
--------
>>> # get image from first page
>>> imsave('temp.tif', numpy.random.rand(3, 4, 301, 219))
>>> im = imread('temp.tif', key=0)
>>> im.shape
(4, 301, 219)
>>> # get images from sequence of files
>>> ims = imread(['temp.tif', 'temp.tif'])
>>> ims.shape
(2, 3, 4, 301, 219)
"""
kwargs_file = parse_kwargs(kwargs, 'multifile', 'is_ome')
kwargs_seq = parse_kwargs(kwargs, 'pattern')
if isinstance(files, basestring) and any(i in files for i in '?*'):
files = glob.glob(files)
if not files:
raise ValueError('no files found')
if not hasattr(files, 'seek') and len(files) == 1:
files = files[0]
if isinstance(files, basestring) or hasattr(files, 'seek'):
with TiffFile(files, **kwargs_file) as tif:
return tif.asarray(**kwargs)
else:
with TiffSequence(files, **kwargs_seq) as imseq:
return imseq.asarray(**kwargs)
def imsave(file, data=None, shape=None, dtype=None, bigsize=2**32-2**25,
**kwargs):
"""Write numpy array to TIFF file.
Refer to the TiffWriter class and member functions for documentation.
Parameters
----------
file : str or binary stream
File name or writable binary stream, such as a open file or BytesIO.
data : array_like
Input image. The last dimensions are assumed to be image depth,
height, width, and samples.
If data is None, an empty array of the specified shape and dtype is
saved to file.
shape : tuple
If data is None, shape of an empty array to save to the file.
dtype : numpy.dtype
If data is None, data-type of an empty array to save to the file.
bigsize : int
Create a BigTIFF file if the size of data in bytes is larger than
this threshold and 'imagej' or 'truncate' are not enabled.
By default, the threshold is 4 GB minus 32 MB reserved for metadata.
Use the 'bigtiff' parameter to explicitly specify the type of
file created.
kwargs : dict
Parameters 'append', 'byteorder', 'bigtiff', 'software', and 'imagej',
are passed to TiffWriter().
Other parameters are passed to TiffWriter.save().
Returns
-------
If the image data are written contiguously, return offset and bytecount
of image data in the file.
Examples
--------
>>> # save a RGB image
>>> data = numpy.random.randint(0, 255, (256, 256, 3), 'uint8')
>>> imsave('temp.tif', data, photometric='rgb')
>>> # save a random array and metadata, using compression
>>> data = numpy.random.rand(2, 5, 3, 301, 219)
>>> imsave('temp.tif', data, compress=6, metadata={'axes': 'TZCYX'})
"""
tifargs = parse_kwargs(kwargs, 'append', 'bigtiff', 'byteorder',
'software', 'imagej')
if data is None:
size = product(shape) * numpy.dtype(dtype).itemsize
else:
try:
size = data.nbytes
except Exception:
size = 0
if size > bigsize and 'bigtiff' not in tifargs and not (
tifargs.get('imagej', False) or tifargs.get('truncate', False)):
tifargs['bigtiff'] = True
with TiffWriter(file, **tifargs) as tif:
return tif.save(data, shape, dtype, **kwargs)
def memmap(filename, shape=None, dtype=None, page=None, series=0, mode='r+',
**kwargs):
"""Return memory-mapped numpy array stored in TIFF file.
Memory-mapping requires data stored in native byte order, without tiling,
compression, predictors, etc.
If shape and dtype are provided, existing files will be overwritten or
appended to depending on the 'append' parameter.
Otherwise the image data of a specified page or series in an existing
file will be memory-mapped. By default, the image data of the first page
series is memory-mapped.
Call flush() to write any changes in the array to the file.
Raise ValueError if the image data in the file is not memory-mappable
Parameters
----------
filename : str
Name of the TIFF file which stores the array.
shape : tuple
Shape of the empty array.
dtype : numpy.dtype
Data-type of the empty array.
page : int
Index of the page which image data to memory-map.
series : int
Index of the page series which image data to memory-map.
mode : {'r+', 'r', 'c'}, optional
The file open mode. Default is to open existing file for reading and
writing ('r+').
kwargs : dict
Additional parameters passed to imsave() or TiffFile().
Examples
--------
>>> # create an empty TIFF file and write to memory-mapped image
>>> im = memmap('temp.tif', shape=(256, 256), dtype='float32')
>>> im[255, 255] = 1.0
>>> im.flush()
>>> im.shape, im.dtype
((256, 256), dtype('float32'))
>>> del im
>>> # memory-map image data in a TIFF file
>>> im = memmap('temp.tif', page=0)
>>> im[255, 255]
1.0
"""
if shape is not None and dtype is not None:
# create a new, empty array
kwargs.update(data=None, shape=shape, dtype=dtype, returnoffset=True,
align=TIFF.ALLOCATIONGRANULARITY)
result = imsave(filename, **kwargs)
if result is None:
# TODO: fail before creating file or writing data
raise ValueError("image data is not memory-mappable")
offset = result[0]
else:
# use existing file
with TiffFile(filename, **kwargs) as tif:
if page is not None:
page = tif.pages[page]
if not page.is_memmappable:
raise ValueError("image data is not memory-mappable")
offset, _ = page.is_contiguous
shape = page.shape
dtype = page.dtype
else:
series = tif.series[series]
if series.offset is None:
raise ValueError("image data is not memory-mappable")
shape = series.shape
dtype = series.dtype
offset = series.offset
return numpy.memmap(filename, dtype, mode, offset, shape, 'C')
class lazyattr(object):
"""Attribute whose value is computed on first access."""
# TODO: help() doesn't work
__slots__ = ('func',)
def __init__(self, func):
self.func = func
# self.__name__ = func.__name__
# self.__doc__ = func.__doc__
# self.lock = threading.RLock()
def __get__(self, instance, owner):
# with self.lock:
if instance is None:
return self
try:
value = self.func(instance)
except AttributeError as e:
raise RuntimeError(e)
if value is NotImplemented:
return getattr(super(owner, instance), self.func.__name__)
setattr(instance, self.func.__name__, value)
return value
class TiffWriter(object):
"""Write numpy arrays to TIFF file.
TiffWriter instances must be closed using the 'close' method, which is
automatically called when using the 'with' context manager.
TiffWriter's main purpose is saving nD numpy array's as TIFF,
not to create any possible TIFF format. Specifically, JPEG compression,
SubIFDs, ExifIFD, or GPSIFD tags are not supported.
Examples
--------
>>> # successively append images to BigTIFF file
>>> data = numpy.random.rand(2, 5, 3, 301, 219)
>>> with TiffWriter('temp.tif', bigtiff=True) as tif:
... for i in range(data.shape[0]):
... tif.save(data[i], compress=6)
"""
def __init__(self, file, bigtiff=False, byteorder=None,
software='tifffile.py', append=False, imagej=False):
"""Open a TIFF file for writing.
An empty TIFF file is created if the file does not exist, else the
file is overwritten with an empty empty TIFF file unless 'append'
is true. Use bigtiff=True when creating files larger than 4 GB.
Parameters
----------
file : str, binary stream, or FileHandle
File name or writable binary stream, such as a open file
or BytesIO.
bigtiff : bool
If True, the BigTIFF format is used.
byteorder : {'<', '>'}
The endianness of the data in the file.
By default, this is the system's native byte order.
software : str
Name of the software used to create the file.
Saved with the first page in the file only.
Must be 7-bit ASCII.
append : bool
If True and 'file' is an existing standard TIFF file, image data
and tags are appended to the file.
Appending data may corrupt specifically formatted TIFF files
such as LSM, STK, ImageJ, NIH, or FluoView.
imagej : bool
If True, write an ImageJ hyperstack compatible file.
This format can handle data types uint8, uint16, or float32 and
data shapes up to 6 dimensions in TZCYXS order.
RGB images (S=3 or S=4) must be uint8.
ImageJ's default byte order is big endian but this implementation
uses the system's native byte order by default.
ImageJ does not support BigTIFF format or LZMA compression.
The ImageJ file format is undocumented.
"""
if append:
# determine if file is an existing TIFF file that can be extended
try:
with FileHandle(file, mode='rb', size=0) as fh:
pos = fh.tell()
try:
with TiffFile(fh) as tif:
if (append != 'force' and
any(getattr(tif, 'is_'+a) for a in (
'lsm', 'stk', 'imagej', 'nih',
'fluoview', 'micromanager'))):
raise ValueError("file contains metadata")
byteorder = tif.byteorder
bigtiff = tif.is_bigtiff
self._ifdoffset = tif.pages.next_page_offset
if tif.pages:
software = None
except Exception as e:
raise ValueError("can not append to file: %s" % str(e))
finally:
fh.seek(pos)
except (IOError, FileNotFoundError):
append = False
if byteorder in (None, '='):
byteorder = '<' if sys.byteorder == 'little' else '>'
elif byteorder not in ('<', '>'):
raise ValueError("invalid byteorder %s" % byteorder)
if imagej and bigtiff:
warnings.warn("writing incompatible BigTIFF ImageJ")
self._byteorder = byteorder
self._software = software
self._imagej = bool(imagej)
self._truncate = False
self._metadata = None
self._colormap = None
self._descriptionoffset = 0
self._descriptionlen = 0
self._descriptionlenoffset = 0
self._tags = None
self._shape = None # normalized shape of data in consecutive pages
self._datashape = None # shape of data in consecutive pages
self._datadtype = None # data type
self._dataoffset = None # offset to data
self._databytecounts = None # byte counts per plane
self._tagoffsets = None # strip or tile offset tag code
if bigtiff:
self._bigtiff = True
self._offsetsize = 8
self._tagsize = 20
self._tagnoformat = 'Q'
self._offsetformat = 'Q'
self._valueformat = '8s'
else:
self._bigtiff = False
self._offsetsize = 4
self._tagsize = 12
self._tagnoformat = 'H'
self._offsetformat = 'I'
self._valueformat = '4s'
if append:
self._fh = FileHandle(file, mode='r+b', size=0)
self._fh.seek(0, 2)
else:
self._fh = FileHandle(file, mode='wb', size=0)
self._fh.write({'<': b'II', '>': b'MM'}[byteorder])
if bigtiff:
self._fh.write(struct.pack(byteorder+'HHH', 43, 8, 0))
else:
self._fh.write(struct.pack(byteorder+'H', 42))
# first IFD
self._ifdoffset = self._fh.tell()
self._fh.write(struct.pack(byteorder+self._offsetformat, 0))
def save(self, data=None, shape=None, dtype=None, returnoffset=False,
photometric=None, planarconfig=None, tile=None,
contiguous=True, align=16, truncate=False, compress=0,
colormap=None, description=None, datetime=None, resolution=None,
metadata={}, extratags=()):
"""Write numpy array and tags to TIFF file.
The data shape's last dimensions are assumed to be image depth,
height (length), width, and samples.
If a colormap is provided, the data's dtype must be uint8 or uint16
and the data values are indices into the last dimension of the
colormap.
If shape and dtype are specified, an empty array is saved.
This option can not be used with compression or multiple tiles.
Image data are written in one stripe per plane by default.
Dimensions larger than 2 to 4 (depending on photometric mode, planar
configuration, and SGI mode) are flattened and saved as separate pages.
The 'SampleFormat' and 'BitsPerSample' tags are derived from
the data type.
Parameters
----------
data : numpy.ndarray or None
Input image array.
shape : tuple or None
Shape of the empty array to save. Used only if data is None.
dtype : numpy.dtype or None
Data-type of the empty array to save. Used only if data is None.
returnoffset : bool
If True and the image data in the file is memory-mappable, return
the offset and number of bytes of the image data in the file.
photometric : {'MINISBLACK', 'MINISWHITE', 'RGB', 'PALETTE', 'CFA'}
The color space of the image data.
By default, this setting is inferred from the data shape and the
value of colormap.
For CFA images, DNG tags must be specified in extratags.
planarconfig : {'CONTIG', 'SEPARATE'}
Specifies if samples are stored contiguous or in separate planes.
By default, this setting is inferred from the data shape.
If this parameter is set, extra samples are used to store grayscale
images.
'CONTIG': last dimension contains samples.
'SEPARATE': third last dimension contains samples.
tile : tuple of int
The shape (depth, length, width) of image tiles to write.
If None (default), image data are written in one stripe per plane.
The tile length and width must be a multiple of 16.
If the tile depth is provided, the SGI ImageDepth and TileDepth
tags are used to save volume data.
Unless a single tile is used, tiles cannot be used to write
contiguous files.
Few software can read the SGI format, e.g. MeVisLab.
contiguous : bool
If True (default) and the data and parameters are compatible with
previous ones, if any, the image data are stored contiguously after
the previous one. Parameters 'photometric' and 'planarconfig'
are ignored. Parameters 'description', datetime', and 'extratags'
are written to the first page of a contiguous series only.
align : int
Byte boundary on which to align the image data in the file.
Default 16. Use mmap.ALLOCATIONGRANULARITY for memory-mapped data.
Following contiguous writes are not aligned.
truncate : bool
If True, only write the first page including shape metadata if
possible (uncompressed, contiguous, not tiled).
Other TIFF readers will only be able to read part of the data.
compress : int or 'LZMA'
Values from 0 to 9 controlling the level of zlib compression.
If 0, data are written uncompressed (default).
Compression cannot be used to write contiguous files.
If 'LZMA', LZMA compression is used, which is not available on
all platforms.
colormap : numpy.ndarray
RGB color values for the corresponding data value.
Must be of shape (3, 2**(data.itemsize*8)) and dtype uint16.
description : str
The subject of the image. Must be 7-bit ASCII. Cannot be used with
the ImageJ format. Saved with the first page only.
datetime : datetime
Date and time of image creation. If None (default), the current
date and time is used. Saved with the first page only.
resolution : (float, float[, str]) or ((int, int), (int, int)[, str])
X and Y resolutions in pixels per resolution unit as float or
rational numbers. A third, optional parameter specifies the
resolution unit, which must be None (default for ImageJ),
'INCH' (default), or 'CENTIMETER'.
metadata : dict
Additional meta data to be saved along with shape information
in JSON or ImageJ formats in an ImageDescription tag.
If None, do not write a second ImageDescription tag.
Strings must be 7-bit ASCII. Saved with the first page only.
extratags : sequence of tuples
Additional tags as [(code, dtype, count, value, writeonce)].
code : int
The TIFF tag Id.
dtype : str
Data type of items in 'value' in Python struct format.
One of B, s, H, I, 2I, b, h, i, 2i, f, d, Q, or q.
count : int
Number of data values. Not used for string or byte string
values.
value : sequence
'Count' values compatible with 'dtype'.
Byte strings must contain count values of dtype packed as
binary data.
writeonce : bool
If True, the tag is written to the first page only.
"""
# TODO: refactor this function
fh = self._fh
byteorder = self._byteorder
if data is None:
if compress:
raise ValueError("can not save compressed empty file")
datashape = shape
datadtype = numpy.dtype(dtype).newbyteorder(byteorder)
datadtypechar = datadtype.char
data = None
else:
data = numpy.asarray(data, byteorder+data.dtype.char, 'C')
if data.size == 0:
raise ValueError("can not save empty array")
datashape = data.shape
datadtype = data.dtype
datadtypechar = data.dtype.char
returnoffset = returnoffset and datadtype.isnative
datasize = product(datashape) * datadtype.itemsize
# just append contiguous data if possible
self._truncate = bool(truncate)
if self._datashape:
if (not contiguous
or self._datashape[1:] != datashape
or self._datadtype != datadtype
or (compress and self._tags)
or tile
or not numpy.array_equal(colormap, self._colormap)):
# incompatible shape, dtype, compression mode, or colormap
self._write_remaining_pages()
self._write_image_description()
self._truncate = False
self._descriptionoffset = 0
self._descriptionlenoffset = 0
self._datashape = None
self._colormap = None
if self._imagej:
raise ValueError(
"ImageJ does not support non-contiguous data")
else:
# consecutive mode
self._datashape = (self._datashape[0] + 1,) + datashape
if not compress:
# write contiguous data, write ifds/tags later
offset = fh.tell()
if data is None:
fh.write_empty(datasize)
else:
fh.write_array(data)
if returnoffset:
return offset, datasize
return
input_shape = datashape
tagnoformat = self._tagnoformat
valueformat = self._valueformat
offsetformat = self._offsetformat
offsetsize = self._offsetsize
tagsize = self._tagsize
MINISBLACK = TIFF.PHOTOMETRIC.MINISBLACK
RGB = TIFF.PHOTOMETRIC.RGB
CFA = TIFF.PHOTOMETRIC.CFA
PALETTE = TIFF.PHOTOMETRIC.PALETTE
CONTIG = TIFF.PLANARCONFIG.CONTIG
SEPARATE = TIFF.PLANARCONFIG.SEPARATE
if photometric is not None:
photometric = enumarg(TIFF.PHOTOMETRIC, photometric)
if planarconfig:
planarconfig = enumarg(TIFF.PLANARCONFIG, planarconfig)
# prepare compression
if not compress:
compress = False
compresstag = 1
elif compress == 'LZMA':
compress = lzma.compress
compresstag = 34925
if self._imagej:
raise ValueError("ImageJ can not handle LZMA compression")
elif not 0 <= compress <= 9:
raise ValueError("invalid compression level %s" % compress)
elif compress:
def compress(data, level=compress):
return zlib.compress(data, level)
compresstag = 8
# prepare ImageJ format
if self._imagej:
if description:
warnings.warn("not writing description to ImageJ file")
description = None
volume = False
if datadtypechar not in 'BHhf':
raise ValueError(
"ImageJ does not support data type '%s'" % datadtypechar)
ijrgb = photometric == RGB if photometric else None
if datadtypechar not in 'B':
ijrgb = False
ijshape = imagej_shape(datashape, ijrgb)
if ijshape[-1] in (3, 4):
photometric = RGB
if datadtypechar not in 'B':
raise ValueError("ImageJ does not support data type '%s' "
"for RGB" % datadtypechar)
elif photometric is None:
photometric = MINISBLACK
planarconfig = None
if planarconfig == SEPARATE:
raise ValueError("ImageJ does not support planar images")
else:
planarconfig = CONTIG if ijrgb else None
# verify colormap and indices
if colormap is not None:
if datadtypechar not in 'BH':
raise ValueError("invalid data dtype for palette mode")
colormap = numpy.asarray(colormap, dtype=byteorder+'H')
if colormap.shape != (3, 2**(datadtype.itemsize * 8)):
raise ValueError("invalid color map shape")
self._colormap = colormap
# verify tile shape
if tile:
tile = tuple(int(i) for i in tile[:3])
volume = len(tile) == 3
if (len(tile) < 2 or tile[-1] % 16 or tile[-2] % 16 or
any(i < 1 for i in tile)):
raise ValueError("invalid tile shape")
else:
tile = ()
volume = False
# normalize data shape to 5D or 6D, depending on volume:
# (pages, planar_samples, [depth,] height, width, contig_samples)
datashape = reshape_nd(datashape, 3 if photometric == RGB else 2)
shape = datashape
ndim = len(datashape)
samplesperpixel = 1
extrasamples = 0
if volume and ndim < 3:
volume = False
if colormap is not None:
photometric = PALETTE
planarconfig = None
if photometric is None:
photometric = MINISBLACK
if planarconfig == CONTIG:
if ndim > 2 and shape[-1] in (3, 4):
photometric = RGB
elif planarconfig == SEPARATE:
if volume and ndim > 3 and shape[-4] in (3, 4):
photometric = RGB
elif ndim > 2 and shape[-3] in (3, 4):
photometric = RGB
elif ndim > 2 and shape[-1] in (3, 4):
photometric = RGB
elif self._imagej:
photometric = MINISBLACK
elif volume and ndim > 3 and shape[-4] in (3, 4):
photometric = RGB
elif ndim > 2 and shape[-3] in (3, 4):
photometric = RGB
if planarconfig and len(shape) <= (3 if volume else 2):
planarconfig = None
photometric = MINISBLACK
if photometric == RGB:
if len(shape) < 3:
raise ValueError("not a RGB(A) image")
if len(shape) < 4:
volume = False
if planarconfig is None:
if shape[-1] in (3, 4):
planarconfig = CONTIG
elif shape[-4 if volume else -3] in (3, 4):
planarconfig = SEPARATE
elif shape[-1] > shape[-4 if volume else -3]:
planarconfig = SEPARATE
else:
planarconfig = CONTIG
if planarconfig == CONTIG:
datashape = (-1, 1) + shape[(-4 if volume else -3):]
samplesperpixel = datashape[-1]
else:
datashape = (-1,) + shape[(-4 if volume else -3):] + (1,)
samplesperpixel = datashape[1]
if samplesperpixel > 3:
extrasamples = samplesperpixel - 3
elif photometric == CFA:
if len(shape) != 2:
raise ValueError("invalid CFA image")
volume = False
planarconfig = None
datashape = (-1, 1) + shape[-2:] + (1,)
if 50706 not in (et[0] for et in extratags):
raise ValueError("must specify DNG tags for CFA image")
elif planarconfig and len(shape) > (3 if volume else 2):
if planarconfig == CONTIG:
datashape = (-1, 1) + shape[(-4 if volume else -3):]
samplesperpixel = datashape[-1]
else:
datashape = (-1,) + shape[(-4 if volume else -3):] + (1,)
samplesperpixel = datashape[1]
extrasamples = samplesperpixel - 1
else:
planarconfig = None
# remove trailing 1s
while len(shape) > 2 and shape[-1] == 1:
shape = shape[:-1]
if len(shape) < 3:
volume = False
datashape = (-1, 1) + shape[(-3 if volume else -2):] + (1,)
# normalize shape to 6D
assert len(datashape) in (5, 6)
if len(datashape) == 5:
datashape = datashape[:2] + (1,) + datashape[2:]
if datashape[0] == -1:
s0 = product(input_shape) // product(datashape[1:])
datashape = (s0,) + datashape[1:]
shape = datashape
if data is not None:
data = data.reshape(shape)
if tile and not volume:
tile = (1, tile[-2], tile[-1])
if photometric == PALETTE:
if (samplesperpixel != 1 or extrasamples or
shape[1] != 1 or shape[-1] != 1):
raise ValueError("invalid data shape for palette mode")
if photometric == RGB and samplesperpixel == 2:
raise ValueError("not a RGB image (samplesperpixel=2)")
bytestr = bytes if sys.version[0] == '2' else (
lambda x: bytes(x, 'ascii') if isinstance(x, str) else x)
tags = [] # list of (code, ifdentry, ifdvalue, writeonce)
strip_or_tile = 'Tile' if tile else 'Strip'
tagbytecounts = TIFF.TAG_NAMES[strip_or_tile + 'ByteCounts']
tag_offsets = TIFF.TAG_NAMES[strip_or_tile + 'Offsets']
self._tagoffsets = tag_offsets
def pack(fmt, *val):
return struct.pack(byteorder+fmt, *val)
def addtag(code, dtype, count, value, writeonce=False):
# Compute ifdentry & ifdvalue bytes from code, dtype, count, value
# Append (code, ifdentry, ifdvalue, writeonce) to tags list
code = int(TIFF.TAG_NAMES.get(code, code))
try:
tifftype = TIFF.DATA_DTYPES[dtype]
except KeyError:
raise ValueError("unknown dtype %s" % dtype)
rawcount = count
if dtype == 's':
# strings
value = bytestr(value) + b'\0'
count = rawcount = len(value)
rawcount = value.find(b'\0\0')
if rawcount < 0:
rawcount = count
else:
rawcount += 1 # length of string without buffer
value = (value,)
elif isinstance(value, bytes):
# packed binary data
dtsize = struct.calcsize(dtype)
if len(value) % dtsize:
raise ValueError('invalid packed binary data')
count = len(value) // dtsize
if len(dtype) > 1:
count *= int(dtype[:-1])
dtype = dtype[-1]
ifdentry = [pack('HH', code, tifftype),
pack(offsetformat, rawcount)]
ifdvalue = None
if struct.calcsize(dtype) * count <= offsetsize:
# value(s) can be written directly
if isinstance(value, bytes):
ifdentry.append(pack(valueformat, value))
elif count == 1:
if isinstance(value, (tuple, list, numpy.ndarray)):
value = value[0]
ifdentry.append(pack(valueformat, pack(dtype, value)))
else:
ifdentry.append(pack(valueformat,
pack(str(count)+dtype, *value)))
else:
# use offset to value(s)
ifdentry.append(pack(offsetformat, 0))
if isinstance(value, bytes):
ifdvalue = value
elif isinstance(value, numpy.ndarray):
assert value.size == count
assert value.dtype.char == dtype
ifdvalue = value.tostring()
elif isinstance(value, (tuple, list)):
ifdvalue = pack(str(count)+dtype, *value)
else:
ifdvalue = pack(dtype, value)
tags.append((code, b''.join(ifdentry), ifdvalue, writeonce))
def rational(arg, max_denominator=1000000):
# return nominator and denominator from float or two integers
from fractions import Fraction # delayed import
try:
f = Fraction.from_float(arg)
except TypeError:
f = Fraction(arg[0], arg[1])
f = f.limit_denominator(max_denominator)
return f.numerator, f.denominator
if description:
# user provided description
addtag('ImageDescription', 's', 0, description, writeonce=True)
# write shape and metadata to ImageDescription
self._metadata = {} if not metadata else metadata.copy()
if self._imagej:
description = imagej_description(
input_shape, shape[-1] in (3, 4), self._colormap is not None,
**self._metadata)
elif metadata or metadata == {}:
if self._truncate:
self._metadata.update(truncated=True)
description = json_description(input_shape, **self._metadata)
else:
description = None
if description:
# add 64 bytes buffer
# the image description might be updated later with the final shape
description = str2bytes(description, 'ascii')
description += b'\0'*64
self._descriptionlen = len(description)
addtag('ImageDescription', 's', 0, description, writeonce=True)
if self._software:
addtag('Software', 's', 0, self._software, writeonce=True)
self._software = None # only save to first page in file
if datetime is None:
datetime = self._now()
addtag('DateTime', 's', 0, datetime.strftime("%Y:%m:%d %H:%M:%S"),
writeonce=True)
addtag('Compression', 'H', 1, compresstag)
addtag('ImageWidth', 'I', 1, shape[-2])
addtag('ImageLength', 'I', 1, shape[-3])
if tile:
addtag('TileWidth', 'I', 1, tile[-1])
addtag('TileLength', 'I', 1, tile[-2])
if tile[0] > 1:
addtag('ImageDepth', 'I', 1, shape[-4])
addtag('TileDepth', 'I', 1, tile[0])
addtag('NewSubfileType', 'I', 1, 0)
sampleformat = {'u': 1, 'i': 2, 'f': 3, 'c': 6}[datadtype.kind]
addtag('SampleFormat', 'H', samplesperpixel,
(sampleformat,) * samplesperpixel)
addtag('PhotometricInterpretation', 'H', 1, photometric.value)
if colormap is not None:
addtag('ColorMap', 'H', colormap.size, colormap)
addtag('SamplesPerPixel', 'H', 1, samplesperpixel)
if planarconfig and samplesperpixel > 1:
addtag('PlanarConfiguration', 'H', 1, planarconfig.value)
addtag('BitsPerSample', 'H', samplesperpixel,
(datadtype.itemsize * 8,) * samplesperpixel)
else:
addtag('BitsPerSample', 'H', 1, datadtype.itemsize * 8)
if extrasamples:
if photometric == RGB and extrasamples == 1:
addtag('ExtraSamples', 'H', 1, 1) # associated alpha channel
else:
addtag('ExtraSamples', 'H', extrasamples, (0,) * extrasamples)
if resolution:
addtag('XResolution', '2I', 1, rational(resolution[0]))
addtag('YResolution', '2I', 1, rational(resolution[1]))
if len(resolution) > 2:
unit = resolution[2]
if unit is not None:
unit = unit.upper()
unit = {None: 1, 'INCH': 2, 'CM': 3, 'CENTIMETER': 3}[unit]
elif self._imagej:
unit = 1
else:
unit = 2
addtag('ResolutionUnit', 'H', 1, unit)
if not tile:
addtag('RowsPerStrip', 'I', 1, shape[-3]) # * shape[-4]
contiguous = not compress
if tile:
# use one chunk per tile per plane
tiles = ((shape[2] + tile[0] - 1) // tile[0],
(shape[3] + tile[1] - 1) // tile[1],
(shape[4] + tile[2] - 1) // tile[2])
numtiles = product(tiles) * shape[1]
stripbytecounts = [
product(tile) * shape[-1] * datadtype.itemsize] * numtiles
addtag(tagbytecounts, offsetformat, numtiles, stripbytecounts)
addtag(tag_offsets, offsetformat, numtiles, [0] * numtiles)
contiguous = contiguous and product(tiles) == 1
if not contiguous:
# allocate tile buffer
chunk = numpy.empty(tile + (shape[-1],), dtype=datadtype)
else:
# use one strip per plane
stripbytecounts = [
product(datashape[2:]) * datadtype.itemsize] * shape[1]
addtag(tagbytecounts, offsetformat, shape[1], stripbytecounts)
addtag(tag_offsets, offsetformat, shape[1], [0] * shape[1])
if data is None and not contiguous:
raise ValueError("can not write non-contiguous empty file")
# add extra tags from user
for t in extratags:
addtag(*t)
# TODO: check TIFFReadDirectoryCheckOrder warning in files containing
# multiple tags of same code
# the entries in an IFD must be sorted in ascending order by tag code
tags = sorted(tags, key=lambda x: x[0])
if not (self._bigtiff or self._imagej) and (
fh.tell() + datasize > 2**31-1):
raise ValueError("data too large for standard TIFF file")
# if not compressed or multi-tiled, write the first ifd and then
# all data contiguously; else, write all ifds and data interleaved
for pageindex in range(1 if contiguous else shape[0]):
# update pointer at ifd_offset
pos = fh.tell()
if pos % 2:
# location of IFD must begin on a word boundary
fh.write(b'\0')
pos += 1
fh.seek(self._ifdoffset)
fh.write(pack(offsetformat, pos))
fh.seek(pos)
# write ifdentries
fh.write(pack(tagnoformat, len(tags)))
tag_offset = fh.tell()
fh.write(b''.join(t[1] for t in tags))
self._ifdoffset = fh.tell()
fh.write(pack(offsetformat, 0)) # offset to next IFD
# write tag values and patch offsets in ifdentries, if necessary
for tagindex, tag in enumerate(tags):
if tag[2]:
pos = fh.tell()
if pos % 2:
# tag value is expected to begin on word boundary
fh.write(b'\0')
pos += 1
fh.seek(tag_offset + tagindex*tagsize + offsetsize + 4)
fh.write(pack(offsetformat, pos))
fh.seek(pos)
if tag[0] == tag_offsets:
stripoffsetsoffset = pos
elif tag[0] == tagbytecounts:
strip_bytecounts_offset = pos
elif tag[0] == 270 and tag[2].endswith(b'\0\0\0\0'):
# image description buffer
self._descriptionoffset = pos
self._descriptionlenoffset = (
tag_offset + tagindex * tagsize + 4)
fh.write(tag[2])
# write image data
data_offset = fh.tell()
skip = align - data_offset % align
fh.seek(skip, 1)
data_offset += skip
if compress:
stripbytecounts = []
if contiguous:
if data is None:
fh.write_empty(datasize)
else:
fh.write_array(data)
elif tile:
for plane in data[pageindex]:
for tz in range(tiles[0]):
for ty in range(tiles[1]):
for tx in range(tiles[2]):
c0 = min(tile[0], shape[2] - tz*tile[0])
c1 = min(tile[1], shape[3] - ty*tile[1])
c2 = min(tile[2], shape[4] - tx*tile[2])
chunk[c0:, c1:, c2:] = 0
chunk[:c0, :c1, :c2] = plane[
tz*tile[0]:tz*tile[0]+c0,
ty*tile[1]:ty*tile[1]+c1,
tx*tile[2]:tx*tile[2]+c2]
if compress:
t = compress(chunk)
stripbytecounts.append(len(t))
fh.write(t)
else:
fh.write_array(chunk)
fh.flush()
elif compress:
for plane in data[pageindex]:
plane = compress(plane)
stripbytecounts.append(len(plane))
fh.write(plane)
# update strip/tile offsets and bytecounts if necessary
pos = fh.tell()
for tagindex, tag in enumerate(tags):
if tag[0] == tag_offsets: # strip/tile offsets
if tag[2]:
fh.seek(stripoffsetsoffset)
strip_offset = data_offset
for size in stripbytecounts:
fh.write(pack(offsetformat, strip_offset))
strip_offset += size
else:
fh.seek(tag_offset + tagindex*tagsize + offsetsize + 4)
fh.write(pack(offsetformat, data_offset))
elif tag[0] == tagbytecounts: # strip/tile bytecounts
if compress:
if tag[2]:
fh.seek(strip_bytecounts_offset)
for size in stripbytecounts:
fh.write(pack(offsetformat, size))
else:
fh.seek(tag_offset + tagindex*tagsize +
offsetsize + 4)
fh.write(pack(offsetformat, stripbytecounts[0]))
break
fh.seek(pos)
fh.flush()
# remove tags that should be written only once
if pageindex == 0:
tags = [tag for tag in tags if not tag[-1]]
self._shape = shape
self._datashape = (1,) + input_shape
self._datadtype = datadtype
self._dataoffset = data_offset
self._databytecounts = stripbytecounts
if contiguous:
# write remaining ifds/tags later
self._tags = tags
# return offset and size of image data
if returnoffset:
return data_offset, sum(stripbytecounts)
def _write_remaining_pages(self):
"""Write outstanding IFDs and tags to file."""
if not self._tags or self._truncate:
return
fh = self._fh
byteorder = self._byteorder
offsetformat = self._offsetformat
offsetsize = self._offsetsize
tagnoformat = self._tagnoformat
tagsize = self._tagsize
dataoffset = self._dataoffset
pagedatasize = sum(self._databytecounts)
pageno = self._shape[0] * self._datashape[0] - 1
def pack(fmt, *val):
return struct.pack(byteorder+fmt, *val)
# construct template IFD in memory
# need to patch offsets to next IFD and data before writing to disk
ifd = io.BytesIO()
ifd.write(pack(tagnoformat, len(self._tags)))
tagoffset = ifd.tell()
ifd.write(b''.join(t[1] for t in self._tags))
ifdoffset = ifd.tell()
ifd.write(pack(offsetformat, 0)) # offset to next IFD
# tag values
for tagindex, tag in enumerate(self._tags):
offset2value = tagoffset + tagindex*tagsize + offsetsize + 4
if tag[2]:
pos = ifd.tell()
if pos % 2: # tag value is expected to begin on word boundary
ifd.write(b'\0')
pos += 1
ifd.seek(offset2value)
ifd.write(pack(offsetformat, pos + fh.tell()))
ifd.seek(pos)
ifd.write(tag[2])
if tag[0] == self._tagoffsets:
# save strip/tile offsets for later updates
stripoffset2offset = offset2value
stripoffset2value = pos
elif tag[0] == self._tagoffsets:
# save strip/tile offsets for later updates
stripoffset2offset = None
stripoffset2value = offset2value
# size to word boundary
if ifd.tell() % 2:
ifd.write(b'\0')
# check if all IFDs fit in file
pos = fh.tell()
if not self._bigtiff and pos + ifd.tell() * pageno > 2**32 - 256:
if self._imagej:
warnings.warn("truncating ImageJ file")
return
raise ValueError("data too large for non-BigTIFF file")
for _ in range(pageno):
# update pointer at IFD offset
pos = fh.tell()
fh.seek(self._ifdoffset)
fh.write(pack(offsetformat, pos))
fh.seek(pos)
self._ifdoffset = pos + ifdoffset
# update strip/tile offsets in IFD
dataoffset += pagedatasize # offset to image data
if stripoffset2offset is None:
ifd.seek(stripoffset2value)
ifd.write(pack(offsetformat, dataoffset))
else:
ifd.seek(stripoffset2offset)
ifd.write(pack(offsetformat, pos + stripoffset2value))
ifd.seek(stripoffset2value)
stripoffset = dataoffset
for size in self._databytecounts:
ifd.write(pack(offsetformat, stripoffset))
stripoffset += size
# write ifd entry
fh.write(ifd.getvalue())
self._tags = None
self._datadtype = None
self._dataoffset = None
self._databytecounts = None
# do not reset _shape or _data_shape
def _write_image_description(self):
"""Write meta data to ImageDescription tag."""
if (not self._datashape or self._datashape[0] == 1 or
self._descriptionoffset <= 0):
return
colormapped = self._colormap is not None
if self._imagej:
isrgb = self._shape[-1] in (3, 4)
description = imagej_description(
self._datashape, isrgb, colormapped, **self._metadata)
else:
description = json_description(self._datashape, **self._metadata)
# rewrite description and its length to file
description = description.encode('utf-8')
description = description[:self._descriptionlen-1]
pos = self._fh.tell()
self._fh.seek(self._descriptionoffset)
self._fh.write(description)
self._fh.seek(self._descriptionlenoffset)
self._fh.write(struct.pack(self._byteorder+self._offsetformat,
len(description)+1))
self._fh.seek(pos)
self._descriptionoffset = 0
self._descriptionlenoffset = 0
self._descriptionlen = 0
def _now(self):
"""Return current date and time."""
return datetime.datetime.now()
def close(self):
"""Write remaining pages and close file handle."""
if not self._truncate:
self._write_remaining_pages()
self._write_image_description()
self._fh.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
class TiffFile(object):
"""Read image and metadata from TIFF file.
TiffFile instances must be closed using the 'close' method, which is
automatically called when using the 'with' context manager.
Attributes
----------
pages : TiffPages
Sequence of TIFF pages in file.
series : list of TiffPageSeries
Sequences of closely related TIFF pages. These are computed
from OME, LSM, ImageJ, etc. metadata or based on similarity
of page properties such as shape, dtype, compression, etc.
byteorder : '>', '<'
The endianness of data in the file.
'>': big-endian (Motorola).
'>': little-endian (Intel).
is_flag : bool
If True, file is of a certain format.
Flags are: bigtiff, movie, shaped, ome, imagej, stk, lsm, fluoview,
nih, vista, 'micromanager, metaseries, mdgel, mediacy, tvips, fei,
sem, scn, svs, scanimage, andor, epics, pilatus.
All attributes are read-only.
Examples
--------
>>> # read image array from TIFF file
>>> imsave('temp.tif', numpy.random.rand(5, 301, 219))
>>> with TiffFile('temp.tif') as tif:
... data = tif.asarray()
>>> data.shape
(5, 301, 219)
"""
def __init__(self, arg, name=None, offset=None, size=None,
multifile=True, movie=None, **kwargs):
"""Initialize instance from file.
Parameters
----------
arg : str or open file
Name of file or open file object.
The file objects are closed in TiffFile.close().
name : str
Optional name of file in case 'arg' is a file handle.
offset : int
Optional start position of embedded file. By default, this is
the current file position.
size : int
Optional size of embedded file. By default, this is the number
of bytes from the 'offset' to the end of the file.
multifile : bool
If True (default), series may include pages from multiple files.
Currently applies to OME-TIFF only.
movie : bool
If True, assume that later pages differ from first page only by
data offsets and bytecounts. Significantly increases speed and
reduces memory usage when reading movies with thousands of pages.
Enabling this for non-movie files will result in data corruption
or crashes. Python 3 only.
kwargs : bool
'is_ome': If False, disable processing of OME-XML metadata.
"""
if 'fastij' in kwargs:
del kwargs['fastij']
raise DeprecationWarning("The fastij option will be removed.")
for key, value in kwargs.items():
if key[:3] == 'is_' and key[3:] in TIFF.FILE_FLAGS:
if value is not None and not value:
setattr(self, key, bool(value))
else:
raise TypeError(
"got an unexpected keyword argument '%s'" % key)
fh = FileHandle(arg, mode='rb', name=name, offset=offset, size=size)
self._fh = fh
self._multifile = bool(multifile)
self._files = {fh.name: self} # cache of TiffFiles
try:
fh.seek(0)
try:
byteorder = {b'II': '<', b'MM': '>'}[fh.read(2)]
except KeyError:
raise ValueError("invalid TIFF file")
sys_byteorder = {'big': '>', 'little': '<'}[sys.byteorder]
self.is_native = byteorder == sys_byteorder
version = struct.unpack(byteorder+'H', fh.read(2))[0]
if version == 43:
# BigTiff
self.is_bigtiff = True
offsetsize, zero = struct.unpack(byteorder+'HH', fh.read(4))
if zero or offsetsize != 8:
raise ValueError("invalid BigTIFF file")
self.byteorder = byteorder
self.offsetsize = 8
self.offsetformat = byteorder+'Q'
self.tagnosize = 8
self.tagnoformat = byteorder+'Q'
self.tagsize = 20
self.tagformat1 = byteorder+'HH'
self.tagformat2 = byteorder+'Q8s'
elif version == 42:
self.is_bigtiff = False
self.byteorder = byteorder
self.offsetsize = 4
self.offsetformat = byteorder+'I'
self.tagnosize = 2
self.tagnoformat = byteorder+'H'
self.tagsize = 12
self.tagformat1 = byteorder+'HH'
self.tagformat2 = byteorder+'I4s'
else:
raise ValueError("not a TIFF file")
# file handle is at offset to offset to first page
self.pages = TiffPages(self)
if self.is_lsm and (self.filehandle.size >= 2**32 or
self.pages[0].compression != 1 or
self.pages[1].compression != 1):
self._lsm_load_pages()
self._lsm_fix_strip_offsets()
self._lsm_fix_strip_bytecounts()
elif movie:
self.pages.useframes = True
except Exception:
fh.close()
raise
@property
def filehandle(self):
"""Return file handle."""
return self._fh
@property
def filename(self):
"""Return name of file handle."""
return self._fh.name
@lazyattr
def fstat(self):
"""Return status of file handle as stat_result object."""
try:
return os.fstat(self._fh.fileno())
except Exception: # io.UnsupportedOperation
return None
def close(self):
"""Close open file handle(s)."""
for tif in self._files.values():
tif.filehandle.close()
self._files = {}
def asarray(self, key=None, series=None, out=None, maxworkers=1):
"""Return image data from multiple TIFF pages as numpy array.
By default, the data from the first series is returned.
Parameters
----------
key : int, slice, or sequence of page indices
Defines which pages to return as array.
series : int or TiffPageSeries
Defines which series of pages to return as array.
out : numpy.ndarray, str, or file-like object; optional
Buffer where image data will be saved.
If numpy.ndarray, a writable array of compatible dtype and shape.
If str or open file, the file name or file object used to
create a memory-map to an array stored in a binary file on disk.
maxworkers : int
Maximum number of threads to concurrently get data from pages.
Default is 1. If None, up to half the CPU cores are used.
Reading data from file is limited to a single thread.
Using multiple threads can significantly speed up this function
if the bottleneck is decoding compressed data.
If the bottleneck is I/O or pure Python code, using multiple
threads might be detrimental.
"""
if not self.pages:
return numpy.array([])
if key is None and series is None:
series = 0
if series is not None:
try:
series = self.series[series]
except (KeyError, TypeError):
pass
pages = series.pages
else:
pages = self.pages
if key is None:
pass
elif isinstance(key, inttypes):
pages = [pages[key]]
elif isinstance(key, slice):
pages = pages[key]
elif isinstance(key, collections.Iterable):
pages = [pages[k] for k in key]
else:
raise TypeError("key must be an int, slice, or sequence")
if not pages:
raise ValueError("no pages selected")
if self.is_nih:
result = stack_pages(pages, out=out, maxworkers=maxworkers,
squeeze=False)
elif key is None and series and series.offset:
if out == 'memmap' and pages[0].is_memmappable:
result = self.filehandle.memmap_array(
series.dtype, series.shape, series.offset)
else:
if out is not None:
out = create_output(out, series.shape, series.dtype)
self.filehandle.seek(series.offset)
i = product(series.shape)
result = self.filehandle.read_array(series.dtype, i, out=out)
if not self.is_native:
result.byteswap(True)
elif len(pages) == 1:
result = pages[0].asarray(out=out)
else:
result = stack_pages(pages, out=out, maxworkers=maxworkers)
if result is None:
return
if key is None:
try:
result.shape = series.shape
except ValueError:
try:
warnings.warn("failed to reshape %s to %s" % (
result.shape, series.shape))
# try series of expected shapes
result.shape = (-1,) + series.shape
except ValueError:
# revert to generic shape
result.shape = (-1,) + pages[0].shape
elif len(pages) == 1:
result.shape = pages[0].shape
else:
result.shape = (-1,) + pages[0].shape
return result
@lazyattr
def series(self):
"""Return related pages as TiffPageSeries.
Side effect: after calling this function, TiffFile.pages might contain
TiffPage and TiffFrame instances.
"""
if not self.pages:
return []
useframes = self.pages.useframes
keyframe = self.pages.keyframe
series = []
for name in 'ome imagej lsm fluoview nih mdgel shaped'.split():
if getattr(self, 'is_' + name, False):
series = getattr(self, '_%s_series' % name)()
break
if not series:
self.pages.useframes = useframes
self.pages.keyframe = keyframe
series = self._generic_series()
# remove empty series, e.g. in MD Gel files
series = [s for s in series if sum(s.shape) > 0]
for i, s in enumerate(series):
s.index = i
return series
def _generic_series(self):
"""Return image series in file."""
if self.pages.useframes:
# movie mode
page = self.pages[0]
shape = page.shape
axes = page.axes
if len(self.pages) > 1:
shape = (len(self.pages),) + shape
axes = 'I' + axes
return [TiffPageSeries(self.pages[:], shape, page.dtype, axes,
stype='movie')]
self.pages.clear(False)
self.pages.load()
result = []
keys = []
series = {}
compressions = TIFF.DECOMPESSORS
for page in self.pages:
if not page.shape:
continue
key = page.shape + (page.axes, page.compression in compressions)
if key in series:
series[key].append(page)
else:
keys.append(key)
series[key] = [page]
for key in keys:
pages = series[key]
page = pages[0]
shape = page.shape
axes = page.axes
if len(pages) > 1:
shape = (len(pages),) + shape
axes = 'I' + axes
result.append(TiffPageSeries(pages, shape, page.dtype, axes,
stype='Generic'))
return result
def _shaped_series(self):
"""Return image series in "shaped" file."""
pages = self.pages
pages.useframes = True
lenpages = len(pages)
def append_series(series, pages, axes, shape, reshape, name):
page = pages[0]
if not axes:
shape = page.shape
axes = page.axes
if len(pages) > 1:
shape = (len(pages),) + shape
axes = 'Q' + axes
size = product(shape)
resize = product(reshape)
if page.is_contiguous and resize > size and resize % size == 0:
# truncated file
axes = 'Q' + axes
shape = (resize // size,) + shape
try:
axes = reshape_axes(axes, shape, reshape)
shape = reshape
except ValueError as e:
warnings.warn(str(e))
series.append(TiffPageSeries(pages, shape, page.dtype, axes,
name=name, stype='Shaped'))
keyframe = axes = shape = reshape = name = None
series = []
index = 0
while True:
if index >= lenpages:
break
# new keyframe; start of new series
pages.keyframe = index
keyframe = pages[index]
if not keyframe.is_shaped:
warnings.warn("invalid shape metadata or corrupted file")
return
# read metadata
axes = None
shape = None
metadata = json_description_metadata(keyframe.is_shaped)
name = metadata.get('name', '')
reshape = metadata['shape']
truncated = metadata.get('truncated', False)
if 'axes' in metadata:
axes = metadata['axes']
if len(axes) == len(reshape):
shape = reshape
else:
axes = ''
warnings.warn("axes do not match shape")
# skip pages if possible
spages = [keyframe]
size = product(reshape)
npages, mod = divmod(size, product(keyframe.shape))
if mod:
warnings.warn("series shape not matching page shape")
return
if 1 < npages <= lenpages - index:
size *= keyframe._dtype.itemsize
if truncated:
npages = 1
elif not (keyframe.is_final and
keyframe.offset + size < pages[index+1].offset):
# need to read all pages for series
for j in range(index+1, index+npages):
page = pages[j]
page.keyframe = keyframe
spages.append(page)
append_series(series, spages, axes, shape, reshape, name)
index += npages
return series
def _imagej_series(self):
"""Return image series in ImageJ file."""
# ImageJ's dimension order is always TZCYXS
# TODO: fix loading of color, composite or palette images
self.pages.useframes = True
self.pages.keyframe = 0
ij = self.imagej_metadata
pages = self.pages
page = pages[0]
def is_hyperstack():
# ImageJ hyperstack store all image metadata in the first page and
# image data is stored contiguously before the second page, if any.
if not page.is_final:
return False
images = ij.get('images', 0)
if images <= 1:
return False
offset, count = page.is_contiguous
if (count != product(page.shape) * page.bitspersample // 8
or offset + count*images > self.filehandle.size):
raise ValueError()
# check that next page is stored after data
if len(pages) > 1 and offset + count*images > pages[1].offset:
return False
return True
try:
hyperstack = is_hyperstack()
except ValueError:
warnings.warn("invalid ImageJ metadata or corrupted file")
return
if hyperstack:
# no need to read other pages
pages = [page]
else:
self.pages.load()
shape = []
axes = []
if 'frames' in ij:
shape.append(ij['frames'])
axes.append('T')
if 'slices' in ij:
shape.append(ij['slices'])
axes.append('Z')
if 'channels' in ij and not (page.photometric == 2 and not
ij.get('hyperstack', False)):
shape.append(ij['channels'])
axes.append('C')
remain = ij.get('images', len(pages))//(product(shape) if shape else 1)
if remain > 1:
shape.append(remain)
axes.append('I')
if page.axes[0] == 'I':
# contiguous multiple images
shape.extend(page.shape[1:])
axes.extend(page.axes[1:])
elif page.axes[:2] == 'SI':
# color-mapped contiguous multiple images
shape = page.shape[0:1] + tuple(shape) + page.shape[2:]
axes = list(page.axes[0]) + axes + list(page.axes[2:])
else:
shape.extend(page.shape)
axes.extend(page.axes)
return [TiffPageSeries(pages, shape, page.dtype, axes, stype='ImageJ')]
def _fluoview_series(self):
"""Return image series in FluoView file."""
self.pages.useframes = True
self.pages.keyframe = 0
self.pages.load()
mm = self.fluoview_metadata
mmhd = list(reversed(mm['Dimensions']))
axes = ''.join(TIFF.MM_DIMENSIONS.get(i[0].upper(), 'Q')
for i in mmhd if i[1] > 1)
shape = tuple(int(i[1]) for i in mmhd if i[1] > 1)
return [TiffPageSeries(self.pages, shape, self.pages[0].dtype, axes,
name=mm['ImageName'], stype='FluoView')]
def _mdgel_series(self):
"""Return image series in MD Gel file."""
# only a single page, scaled according to metadata in second page
self.pages.useframes = False
self.pages.keyframe = 0
self.pages.load()
md = self.mdgel_metadata
if md['FileTag'] in (2, 128):
dtype = numpy.dtype('float32')
scale = md['ScalePixel']
scale = scale[0] / scale[1] # rational
if md['FileTag'] == 2:
# squary root data format
def transform(a):
return a.astype('float32')**2 * scale
else:
def transform(a):
return a.astype('float32') * scale
else:
transform = None
page = self.pages[0]
return [TiffPageSeries([page], page.shape, dtype, page.axes,
transform=transform, stype='MDGel')]
def _nih_series(self):
"""Return image series in NIH file."""
self.pages.useframes = True
self.pages.keyframe = 0
self.pages.load()
page0 = self.pages[0]
if len(self.pages) == 1:
shape = page0.shape
axes = page0.axes
else:
shape = (len(self.pages),) + page0.shape
axes = 'I' + page0.axes
return [
TiffPageSeries(self.pages, shape, page0.dtype, axes, stype='NIH')]
def _ome_series(self):
"""Return image series in OME-TIFF file(s)."""
from xml.etree import cElementTree as etree # delayed import
omexml = self.pages[0].description
try:
root = etree.fromstring(omexml)
except etree.ParseError as e:
# TODO: test badly encoded ome-xml
warnings.warn("ome-xml: %s" % e)
try:
# might work on Python 2
omexml = omexml.decode('utf-8', 'ignore').encode('utf-8')
root = etree.fromstring(omexml)
except Exception:
return
self.pages.useframes = True
self.pages.keyframe = 0
self.pages.load()
uuid = root.attrib.get('UUID', None)
self._files = {uuid: self}
dirname = self._fh.dirname
modulo = {}
series = []
for element in root:
if element.tag.endswith('BinaryOnly'):
warnings.warn("ome-xml: not an ome-tiff master file")
break
if element.tag.endswith('StructuredAnnotations'):
for annot in element:
if not annot.attrib.get('Namespace',
'').endswith('modulo'):
continue
for value in annot:
for modul in value:
for along in modul:
if not along.tag[:-1].endswith('Along'):
continue
axis = along.tag[-1]
newaxis = along.attrib.get('Type', 'other')
newaxis = TIFF.AXES_LABELS[newaxis]
if 'Start' in along.attrib:
step = float(along.attrib.get('Step', 1))
start = float(along.attrib['Start'])
stop = float(along.attrib['End']) + step
labels = numpy.arange(start, stop, step)
else:
labels = [label.text for label in along
if label.tag.endswith('Label')]
modulo[axis] = (newaxis, labels)
if not element.tag.endswith('Image'):
continue
attr = element.attrib
name = attr.get('Name', None)
for pixels in element:
if not pixels.tag.endswith('Pixels'):
continue
attr = pixels.attrib
dtype = attr.get('PixelType', None)
axes = ''.join(reversed(attr['DimensionOrder']))
shape = list(int(attr['Size'+ax]) for ax in axes)
size = product(shape[:-2])
ifds = None
spp = 1 # samples per pixel
for data in pixels:
if data.tag.endswith('Channel'):
attr = data.attrib
if ifds is None:
spp = int(attr.get('SamplesPerPixel', spp))
ifds = [None] * (size // spp)
elif int(attr.get('SamplesPerPixel', 1)) != spp:
raise ValueError(
"Can't handle differing SamplesPerPixel")
continue
if ifds is None:
ifds = [None] * (size // spp)
if not data.tag.endswith('TiffData'):
continue
attr = data.attrib
ifd = int(attr.get('IFD', 0))
num = int(attr.get('NumPlanes', 1 if 'IFD' in attr else 0))
num = int(attr.get('PlaneCount', num))
idx = [int(attr.get('First'+ax, 0)) for ax in axes[:-2]]
try:
idx = numpy.ravel_multi_index(idx, shape[:-2])
except ValueError:
# ImageJ produces invalid ome-xml when cropping
warnings.warn("ome-xml: invalid TiffData index")
continue
for uuid in data:
if not uuid.tag.endswith('UUID'):
continue
if uuid.text not in self._files:
if not self._multifile:
# abort reading multifile OME series
# and fall back to generic series
return []
fname = uuid.attrib['FileName']
try:
tif = TiffFile(os.path.join(dirname, fname))
tif.pages.useframes = True
tif.pages.keyframe = 0
tif.pages.load()
except (IOError, FileNotFoundError, ValueError):
warnings.warn(
"ome-xml: failed to read '%s'" % fname)
break
self._files[uuid.text] = tif
tif.close()
pages = self._files[uuid.text].pages
try:
for i in range(num if num else len(pages)):
ifds[idx + i] = pages[ifd + i]
except IndexError:
warnings.warn("ome-xml: index out of range")
# only process first uuid
break
else:
pages = self.pages
try:
for i in range(num if num else len(pages)):
ifds[idx + i] = pages[ifd + i]
except IndexError:
warnings.warn("ome-xml: index out of range")
if all(i is None for i in ifds):
# skip images without data
continue
# set a keyframe on all ifds
keyframe = None
for i in ifds:
# try find a TiffPage
if i and i == i.keyframe:
keyframe = i
break
if not keyframe:
# reload a TiffPage from file
for i, keyframe in enumerate(ifds):
if keyframe:
keyframe.parent.pages.keyframe = keyframe.index
keyframe = keyframe.parent.pages[keyframe.index]
ifds[i] = keyframe
break
for i in ifds:
if i is not None:
i.keyframe = keyframe
dtype = keyframe.dtype
series.append(
TiffPageSeries(ifds, shape, dtype, axes, parent=self,
name=name, stype='OME'))
for serie in series:
shape = list(serie.shape)
for axis, (newaxis, labels) in modulo.items():
i = serie.axes.index(axis)
size = len(labels)
if shape[i] == size:
serie.axes = serie.axes.replace(axis, newaxis, 1)
else:
shape[i] //= size
shape.insert(i+1, size)
serie.axes = serie.axes.replace(axis, axis+newaxis, 1)
serie.shape = tuple(shape)
# squeeze dimensions
for serie in series:
serie.shape, serie.axes = squeeze_axes(serie.shape, serie.axes)
return series
def _lsm_series(self):
"""Return main image series in LSM file. Skip thumbnails."""
lsmi = self.lsm_metadata
axes = TIFF.CZ_LSMINFO_SCANTYPE[lsmi['ScanType']]
if self.pages[0].photometric == 2: # RGB; more than one channel
axes = axes.replace('C', '').replace('XY', 'XYC')
if lsmi.get('DimensionP', 0) > 1:
axes += 'P'
if lsmi.get('DimensionM', 0) > 1:
axes += 'M'
axes = axes[::-1]
shape = tuple(int(lsmi[TIFF.CZ_LSMINFO_DIMENSIONS[i]]) for i in axes)
name = lsmi.get('Name', '')
self.pages.keyframe = 0
pages = self.pages[::2]
dtype = pages[0].dtype
series = [TiffPageSeries(pages, shape, dtype, axes, name=name,
stype='LSM')]
if self.pages[1].is_reduced:
self.pages.keyframe = 1
pages = self.pages[1::2]
dtype = pages[0].dtype
cp, i = 1, 0
while cp < len(pages) and i < len(shape)-2:
cp *= shape[i]
i += 1
shape = shape[:i] + pages[0].shape
axes = axes[:i] + 'CYX'
series.append(TiffPageSeries(pages, shape, dtype, axes, name=name,
stype='LSMreduced'))
return series
def _lsm_load_pages(self):
"""Load all pages from LSM file."""
self.pages.cache = True
self.pages.useframes = True
# second series: thumbnails
self.pages.keyframe = 1
keyframe = self.pages[1]
for page in self.pages[1::2]:
page.keyframe = keyframe
# first series: data
self.pages.keyframe = 0
keyframe = self.pages[0]
for page in self.pages[::2]:
page.keyframe = keyframe
def _lsm_fix_strip_offsets(self):
"""Unwrap strip offsets for LSM files greater than 4 GB.
Each series and position require separate unwrapping (undocumented).
"""
if self.filehandle.size < 2**32:
return
pages = self.pages
npages = len(pages)
series = self.series[0]
axes = series.axes
# find positions
positions = 1
for i in 0, 1:
if series.axes[i] in 'PM':
positions *= series.shape[i]
# make time axis first
if positions > 1:
ntimes = 0
for i in 1, 2:
if axes[i] == 'T':
ntimes = series.shape[i]
break
if ntimes:
div, mod = divmod(npages, 2*positions*ntimes)
assert mod == 0
shape = (positions, ntimes, div, 2)
indices = numpy.arange(product(shape)).reshape(shape)
indices = numpy.moveaxis(indices, 1, 0)
else:
indices = numpy.arange(npages).reshape(-1, 2)
# images of reduced page might be stored first
if pages[0].dataoffsets[0] > pages[1].dataoffsets[0]:
indices = indices[..., ::-1]
# unwrap offsets
wrap = 0
previousoffset = 0
for i in indices.flat:
page = pages[i]
dataoffsets = []
for currentoffset in page.dataoffsets:
if currentoffset < previousoffset:
wrap += 2**32
dataoffsets.append(currentoffset + wrap)
previousoffset = currentoffset
page.dataoffsets = tuple(dataoffsets)
def _lsm_fix_strip_bytecounts(self):
"""Set databytecounts to size of compressed data.
The StripByteCounts tag in LSM files contains the number of bytes
for the uncompressed data.
"""
pages = self.pages
if pages[0].compression == 1:
return
# sort pages by first strip offset
pages = sorted(pages, key=lambda p: p.dataoffsets[0])
npages = len(pages) - 1
for i, page in enumerate(pages):
if page.index % 2:
continue
offsets = page.dataoffsets
bytecounts = page.databytecounts
if i < npages:
lastoffset = pages[i+1].dataoffsets[0]
else:
# LZW compressed strips might be longer than uncompressed
lastoffset = min(offsets[-1] + 2*bytecounts[-1], self._fh.size)
offsets = offsets + (lastoffset,)
page.databytecounts = tuple(offsets[j+1] - offsets[j]
for j in range(len(bytecounts)))
def __getattr__(self, name):
"""Return 'is_flag' attributes from first page."""
if name[3:] in TIFF.FILE_FLAGS:
if not self.pages:
return False
value = bool(getattr(self.pages[0], name))
setattr(self, name, value)
return value
raise AttributeError("'%s' object has no attribute '%s'" %
(self.__class__.__name__, name))
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def __str__(self, detail=0):
"""Return string containing information about file.
The detail parameter specifies the level of detail returned:
0: file only.
1: all series, first page of series and its tags.
2: large tag values and file metadata.
3: all pages.
"""
info = [
"TiffFile '%s'" % snipstr(self._fh.name, 32),
format_size(self._fh.size),
{'<': 'LittleEndian', '>': 'BigEndian'}[self.byteorder]]
if self.is_bigtiff:
info.append('BigTiff')
info.append('|'.join(f.upper() for f in self.flags))
if len(self.pages) > 1:
info.append('%i Pages' % len(self.pages))
if len(self.series) > 1:
info.append('%i Series' % len(self.series))
if len(self._files) > 1:
info.append('%i Files' % (len(self._files)))
info = ' '.join(info)
if detail <= 0:
return info
info = [info]
info.append('\n'.join(str(s) for s in self.series))
if detail >= 3:
info.extend((TiffPage.__str__(p, detail=detail)
for p in self.pages
if p is not None))
else:
info.extend((TiffPage.__str__(s.pages[0], detail=detail)
for s in self.series
if s.pages[0] is not None))
if detail >= 2:
for name in sorted(self.flags):
if hasattr(self, name + '_metadata'):
m = getattr(self, name + '_metadata')
if m:
info.append(
"%s_METADATA\n%s" % (name.upper(), pformat(m)))
return '\n\n'.join(info).replace('\n\n\n', '\n\n')
@lazyattr
def flags(self):
"""Return set of file flags."""
return set(name.lower() for name in sorted(TIFF.FILE_FLAGS)
if getattr(self, 'is_' + name))
@lazyattr
def is_mdgel(self):
"""File has MD Gel format."""
try:
return self.pages[0].is_mdgel or self.pages[1].is_mdgel
except IndexError:
return False
@property
def is_movie(self):
"""Return if file is a movie."""
return self.pages.useframes
@lazyattr
def shaped_metadata(self):
"""Return Tifffile metadata from JSON descriptions as dicts."""
if not self.is_shaped:
return
return tuple(json_description_metadata(s.pages[0].is_shaped)
for s in self.series if s.stype.lower() == 'shaped')
@lazyattr
def ome_metadata(self):
"""Return OME XML as dict."""
if not self.is_ome:
return
return xml2dict(self.pages[0].description)
@lazyattr
def lsm_metadata(self):
"""Return LSM metadata from CZ_LSMINFO tag as dict."""
if not self.is_lsm:
return
return self.pages[0].tags['CZ_LSMINFO'].value
@lazyattr
def stk_metadata(self):
"""Return STK metadata from UIC tags as dict."""
if not self.is_stk:
return
page = self.pages[0]
tags = page.tags
result = {}
result['NumberPlanes'] = tags['UIC2tag'].count
if page.description:
result['PlaneDescriptions'] = page.description.split('\0')
# result['plane_descriptions'] = stk_description_metadata(
# page.image_description)
if 'UIC1tag' in tags:
result.update(tags['UIC1tag'].value)
if 'UIC3tag' in tags:
result.update(tags['UIC3tag'].value) # wavelengths
if 'UIC4tag' in tags:
result.update(tags['UIC4tag'].value) # override uic1 tags
uic2tag = tags['UIC2tag'].value
result['ZDistance'] = uic2tag['ZDistance']
result['TimeCreated'] = uic2tag['TimeCreated']
result['TimeModified'] = uic2tag['TimeModified']
try:
result['DatetimeCreated'] = numpy.array(
[julian_datetime(*dt) for dt in
zip(uic2tag['DateCreated'], uic2tag['TimeCreated'])],
dtype='datetime64[ns]')
result['DatetimeModified'] = numpy.array(
[julian_datetime(*dt) for dt in
zip(uic2tag['DateModified'], uic2tag['TimeModified'])],
dtype='datetime64[ns]')
except ValueError as e:
warnings.warn("stk_metadata: %s" % e)
return result
@lazyattr
def imagej_metadata(self):
"""Return consolidated ImageJ metadata as dict."""
if not self.is_imagej:
return
page = self.pages[0]
result = imagej_description_metadata(page.is_imagej)
if 'IJMetadata' in page.tags:
try:
result.update(page.tags['IJMetadata'].value)
except Exception:
pass
return result
@lazyattr
def fluoview_metadata(self):
"""Return consolidated FluoView metadata as dict."""
if not self.is_fluoview:
return
result = {}
page = self.pages[0]
result.update(page.tags['MM_Header'].value)
# TODO: read stamps from all pages
result['Stamp'] = page.tags['MM_Stamp'].value
# skip parsing image description; not reliable
# try:
# t = fluoview_description_metadata(page.image_description)
# if t is not None:
# result['ImageDescription'] = t
# except Exception as e:
# warnings.warn(
# "failed to read FluoView image description: %s" % e)
return result
@lazyattr
def nih_metadata(self):
"""Return NIH Image metadata from NIHImageHeader tag as dict."""
if not self.is_nih:
return
return self.pages[0].tags['NIHImageHeader'].value
@lazyattr
def fei_metadata(self):
"""Return FEI metadata from SFEG or HELIOS tags as dict."""
if not self.is_fei:
return
tags = self.pages[0].tags
if 'FEI_SFEG' in tags:
return tags['FEI_SFEG'].value
if 'FEI_HELIOS' in tags:
return tags['FEI_HELIOS'].value
@lazyattr
def sem_metadata(self):
"""Return SEM metadata from CZ_SEM tag as dict."""
if not self.is_sem:
return
return self.pages[0].tags['CZ_SEM'].value
@lazyattr
def mdgel_metadata(self):
"""Return consolidated metadata from MD GEL tags as dict."""
for page in self.pages[:2]:
if 'MDFileTag' in page.tags:
tags = page.tags
break
else:
return
result = {}
for code in range(33445, 33453):
name = TIFF.TAGS[code]
if name not in tags:
continue
result[name[2:]] = tags[name].value
return result
@lazyattr
def andor_metadata(self):
"""Return Andor tags as dict."""
return self.pages[0].andor_tags
@lazyattr
def epics_metadata(self):
"""Return EPICS areaDetector tags as dict."""
return self.pages[0].epics_tags
@lazyattr
def tvips_metadata(self):
"""Return TVIPS tag as dict."""
if not self.is_tvips:
return
return self.pages[0].tags['TVIPS'].value
@lazyattr
def metaseries_metadata(self):
"""Return MetaSeries metadata from image description as dict."""
if not self.is_metaseries:
return
return metaseries_description_metadata(self.pages[0].description)
@lazyattr
def pilatus_metadata(self):
"""Return Pilatus metadata from image description as dict."""
if not self.is_pilatus:
return
return pilatus_description_metadata(self.pages[0].description)
@lazyattr
def micromanager_metadata(self):
"""Return consolidated MicroManager metadata as dict."""
if not self.is_micromanager:
return
# from file header
result = read_micromanager_metadata(self._fh)
# from tag
result.update(self.pages[0].tags['MicroManagerMetadata'].value)
return result
@lazyattr
def scanimage_metadata(self):
"""Return ScanImage non-varying frame and ROI metadata as dict."""
if not self.is_scanimage:
return
result = {}
try:
framedata, roidata = read_scanimage_metadata(self._fh)
result['FrameData'] = framedata
result.update(roidata)
except ValueError:
pass
# TODO: scanimage_artist_metadata
try:
result['Description'] = scanimage_description_metadata(
self.pages[0].description)
except Exception as e:
warnings.warn("scanimage_description_metadata failed: %s" % e)
return result
class TiffPages(object):
"""Sequence of TIFF image file directories."""
def __init__(self, parent):
"""Initialize instance from file. Read first TiffPage from file.
The file position must be at an offset to an offset to a TiffPage.
"""
self.parent = parent
self.pages = [] # cache of TiffPages, TiffFrames, or their offsets
self.complete = False # True if offsets to all pages were read
self._tiffpage = TiffPage # class for reading tiff pages
self._keyframe = None
self._cache = True
# read offset to first page
fh = parent.filehandle
self._nextpageoffset = fh.tell()
offset = struct.unpack(parent.offsetformat,
fh.read(parent.offsetsize))[0]
if offset == 0:
# warnings.warn("file contains no pages")
self.complete = True
return
if offset >= fh.size:
warnings.warn("invalid page offset (%i)" % offset)
self.complete = True
return
# always read and cache first page
fh.seek(offset)
page = TiffPage(parent, index=0)
self.pages.append(page)
self._keyframe = page
@property
def cache(self):
"""Return if pages/frames are currenly being cached."""
return self._cache
@cache.setter
def cache(self, value):
"""Enable or disable caching of pages/frames. Clear cache if False."""
value = bool(value)
if self._cache and not value:
self.clear()
self._cache = value
@property
def useframes(self):
"""Return if currently using TiffFrame (True) or TiffPage (False)."""
return self._tiffpage == TiffFrame and TiffFrame is not TiffPage
@useframes.setter
def useframes(self, value):
"""Set to use TiffFrame (True) or TiffPage (False)."""
self._tiffpage = TiffFrame if value else TiffPage
@property
def keyframe(self):
"""Return index of current keyframe."""
return self._keyframe.index
@keyframe.setter
def keyframe(self, index):
"""Set current keyframe. Load TiffPage from file if necessary."""
if self.complete or 0 <= index < len(self.pages):
page = self.pages[index]
if isinstance(page, TiffPage):
self._keyframe = page
return
elif isinstance(page, TiffFrame):
# remove existing frame
self.pages[index] = page.offset
# load TiffPage from file
useframes = self.useframes
self._tiffpage = TiffPage
self._keyframe = self[index]
self.useframes = useframes
@property
def next_page_offset(self):
"""Return offset where offset to a new page can be stored."""
if not self.complete:
self._seek(-1)
return self._nextpageoffset
def load(self):
"""Read all remaining pages from file."""
fh = self.parent.filehandle
keyframe = self._keyframe
pages = self.pages
if not self.complete:
self._seek(-1)
for i, page in enumerate(pages):
if isinstance(page, inttypes):
fh.seek(page)
page = self._tiffpage(self.parent, index=i, keyframe=keyframe)
pages[i] = page
def clear(self, fully=True):
"""Delete all but first page from cache. Set keyframe to first page."""
pages = self.pages
if not self._cache or len(pages) < 1:
return
self._keyframe = pages[0]
if fully:
# delete all but first TiffPage/TiffFrame
for i, page in enumerate(pages[1:]):
if not isinstance(page, inttypes):
pages[i+1] = page.offset
elif TiffFrame is not TiffPage:
# delete only TiffFrames
for i, page in enumerate(pages):
if isinstance(page, TiffFrame):
pages[i] = page.offset
def _seek(self, index):
"""Seek file to offset of specified page."""
pages = self.pages
if not pages:
return
fh = self.parent.filehandle
if fh.closed:
raise RuntimeError("FileHandle is closed")
if self.complete or 0 <= index < len(pages):
page = pages[index]
offset = page if isinstance(page, inttypes) else page.offset
fh.seek(offset)
return
offsetformat = self.parent.offsetformat
offsetsize = self.parent.offsetsize
tagnoformat = self.parent.tagnoformat
tagnosize = self.parent.tagnosize
tagsize = self.parent.tagsize
unpack = struct.unpack
page = pages[-1]
offset = page if isinstance(page, inttypes) else page.offset
while True:
# read offsets to pages from file until index is reached
fh.seek(offset)
# skip tags
try:
tagno = unpack(tagnoformat, fh.read(tagnosize))[0]
if tagno > 4096:
raise ValueError("suspicious number of tags")
except Exception:
warnings.warn("corrupted tag list at offset %i" % offset)
del pages[-1]
self.complete = True
break
self._nextpageoffset = offset + tagnosize + tagno * tagsize
fh.seek(self._nextpageoffset)
# read offset to next page
offset = unpack(offsetformat, fh.read(offsetsize))[0]
if offset == 0:
self.complete = True
break
if offset >= fh.size:
warnings.warn("invalid page offset (%i)" % offset)
self.complete = True
break
pages.append(offset)
if 0 <= index < len(pages):
break
if index >= len(pages):
raise IndexError('list index out of range')
page = pages[index]
fh.seek(page if isinstance(page, inttypes) else page.offset)
def __bool__(self):
"""Return True if file contains any pages."""
return len(self.pages) > 0
def __len__(self):
"""Return number of pages in file."""
if not self.complete:
self._seek(-1)
return len(self.pages)
def __getitem__(self, key):
"""Return specified page(s) from cache or file."""
pages = self.pages
if not pages:
raise IndexError('list index out of range')
if key is 0:
return pages[key]
if isinstance(key, slice):
start, stop, _ = key.indices(2**31)
if not self.complete and max(stop, start) > len(pages):
self._seek(-1)
return [self[i] for i in range(*key.indices(len(pages)))]
if self.complete and key >= len(pages):
raise IndexError('list index out of range')
try:
page = pages[key]
except IndexError:
page = 0
if not isinstance(page, inttypes):
return page
self._seek(key)
page = self._tiffpage(self.parent, index=key, keyframe=self._keyframe)
if self._cache:
pages[key] = page
return page
def __iter__(self):
"""Return iterator over all pages."""
i = 0
while True:
try:
yield self[i]
i += 1
except IndexError:
break
class TiffPage(object):
"""TIFF image file directory (IFD).
Attributes
----------
index : int
Index of page in file.
dtype : numpy.dtype or None
Data type of the image in IFD.
shape : tuple
Dimensions of the image in IFD.
axes : str
Axes label codes:
'X' width, 'Y' height, 'S' sample, 'I' image series|page|plane,
'Z' depth, 'C' color|em-wavelength|channel, 'E' ex-wavelength|lambda,
'T' time, 'R' region|tile, 'A' angle, 'P' phase, 'H' lifetime,
'L' exposure, 'V' event, 'Q' unknown, '_' missing
tags : dict
Dictionary of tags in IFD. {tag.name: TiffTag}
colormap : numpy.ndarray
Color look up table, if exists.
All attributes are read-only.
Notes
-----
The internal, normalized '_shape' attribute is 6 dimensional:
0 : number planes/images (stk, ij).
1 : planar samplesperpixel.
2 : imagedepth Z (sgi).
3 : imagelength Y.
4 : imagewidth X.
5 : contig samplesperpixel.
"""
# default properties; will be updated from tags
imagewidth = 0
imagelength = 0
imagedepth = 1
tilewidth = 0
tilelength = 0
tiledepth = 1
bitspersample = 1
samplesperpixel = 1
sampleformat = 1
rowsperstrip = 2**32-1
compression = 1
planarconfig = 1
fillorder = 1
photometric = 0
predictor = 1
extrasamples = 1
colormap = None
software = ''
description = ''
description1 = ''
def __init__(self, parent, index, keyframe=None):
"""Initialize instance from file.
The file handle position must be at offset to a valid IFD.
"""
self.parent = parent
self.index = index
self.shape = ()
self._shape = ()
self.dtype = None
self._dtype = None
self.axes = ""
self.tags = {}
self.dataoffsets = ()
self.databytecounts = ()
# read TIFF IFD structure and its tags from file
fh = parent.filehandle
self.offset = fh.tell() # offset to this IDF
try:
tagno = struct.unpack(parent.tagnoformat,
fh.read(parent.tagnosize))[0]
if tagno > 4096:
raise ValueError("suspicious number of tags")
except Exception:
raise ValueError("corrupted tag list at offset %i" % self.offset)
tagsize = parent.tagsize
data = fh.read(tagsize * tagno)
tags = self.tags
index = -tagsize
for _ in range(tagno):
index += tagsize
try:
tag = TiffTag(self.parent, data[index:index+tagsize])
except TiffTag.Error as e:
warnings.warn(str(e))
continue
tagname = tag.name
if tagname not in tags:
name = tagname
tags[name] = tag
else:
# some files contain multiple tags with same code
# e.g. MicroManager files contain two ImageDescription tags
i = 1
while True:
name = "%s%i" % (tagname, i)
if name not in tags:
tags[name] = tag
break
name = TIFF.TAG_ATTRIBUTES.get(name, '')
if name:
setattr(self, name, tag.value)
if not tags:
return # found in FIBICS
# consolidate private tags; remove them from self.tags
if self.is_andor:
self.andor_tags
elif self.is_epics:
self.epics_tags
if self.is_lsm or (self.index and self.parent.is_lsm):
# correct non standard LSM bitspersample tags
self.tags['BitsPerSample']._fix_lsm_bitspersample(self)
if self.is_vista or (self.index and self.parent.is_vista):
# ISS Vista writes wrong ImageDepth tag
self.imagedepth = 1
if self.is_stk and 'UIC1tag' in tags and not tags['UIC1tag'].value:
# read UIC1tag now that plane count is known
uic1tag = tags['UIC1tag']
fh.seek(uic1tag.valueoffset)
tags['UIC1tag'].value = read_uic1tag(
fh, self.parent.byteorder, uic1tag.dtype,
uic1tag.count, None, tags['UIC2tag'].count)
if 'IJMetadata' in tags:
# decode IJMetadata tag
try:
tags['IJMetadata'].value = imagej_metadata(
tags['IJMetadata'].value,
tags['IJMetadataByteCounts'].value,
self.parent.byteorder)
except Exception as e:
warnings.warn(str(e))
if 'BitsPerSample' in tags:
tag = tags['BitsPerSample']
if tag.count == 1:
self.bitspersample = tag.value
else:
# LSM might list more items than samples_per_pixel
value = tag.value[:self.samplesperpixel]
if any((v-value[0] for v in value)):
self.bitspersample = value
else:
self.bitspersample = value[0]
if 'SampleFormat' in tags:
tag = tags['SampleFormat']
if tag.count == 1:
self.sampleformat = tag.value
else:
value = tag.value[:self.samplesperpixel]
if any((v-value[0] for v in value)):
self.sampleformat = value
else:
self.sampleformat = value[0]
if 'ImageLength' in tags:
if 'RowsPerStrip' not in tags or tags['RowsPerStrip'].count > 1:
self.rowsperstrip = self.imagelength
# self.stripsperimage = int(math.floor(
# float(self.imagelength + self.rowsperstrip - 1) /
# self.rowsperstrip))
# determine dtype
dtype = self.sampleformat, self.bitspersample
dtype = TIFF.SAMPLE_DTYPES.get(dtype, None)
if dtype is not None:
dtype = numpy.dtype(dtype)
self.dtype = self._dtype = dtype
# determine shape of data
imagelength = self.imagelength
imagewidth = self.imagewidth
imagedepth = self.imagedepth
samplesperpixel = self.samplesperpixel
if self.is_stk:
assert self.imagedepth == 1
uictag = tags['UIC2tag'].value
planes = tags['UIC2tag'].count
if self.planarconfig == 1:
self._shape = (
planes, 1, 1, imagelength, imagewidth, samplesperpixel)
if samplesperpixel == 1:
self.shape = (planes, imagelength, imagewidth)
self.axes = 'YX'
else:
self.shape = (
planes, imagelength, imagewidth, samplesperpixel)
self.axes = 'YXS'
else:
self._shape = (
planes, samplesperpixel, 1, imagelength, imagewidth, 1)
if samplesperpixel == 1:
self.shape = (planes, imagelength, imagewidth)
self.axes = 'YX'
else:
self.shape = (
planes, samplesperpixel, imagelength, imagewidth)
self.axes = 'SYX'
# detect type of series
if planes == 1:
self.shape = self.shape[1:]
elif numpy.all(uictag['ZDistance'] != 0):
self.axes = 'Z' + self.axes
elif numpy.all(numpy.diff(uictag['TimeCreated']) != 0):
self.axes = 'T' + self.axes
else:
self.axes = 'I' + self.axes
elif self.photometric == 2 or samplesperpixel > 1: # PHOTOMETRIC.RGB
if self.planarconfig == 1:
self._shape = (
1, 1, imagedepth, imagelength, imagewidth, samplesperpixel)
if imagedepth == 1:
self.shape = (imagelength, imagewidth, samplesperpixel)
self.axes = 'YXS'
else:
self.shape = (
imagedepth, imagelength, imagewidth, samplesperpixel)
self.axes = 'ZYXS'
else:
self._shape = (1, samplesperpixel, imagedepth,
imagelength, imagewidth, 1)
if imagedepth == 1:
self.shape = (samplesperpixel, imagelength, imagewidth)
self.axes = 'SYX'
else:
self.shape = (
samplesperpixel, imagedepth, imagelength, imagewidth)
self.axes = 'SZYX'
else:
self._shape = (1, 1, imagedepth, imagelength, imagewidth, 1)
if imagedepth == 1:
self.shape = (imagelength, imagewidth)
self.axes = 'YX'
else:
self.shape = (imagedepth, imagelength, imagewidth)
self.axes = 'ZYX'
# dataoffsets and databytecounts
if 'TileOffsets' in tags:
self.dataoffsets = tags['TileOffsets'].value
elif 'StripOffsets' in tags:
self.dataoffsets = tags['StripOffsets'].value
else:
self.dataoffsets = (0,)
if 'TileByteCounts' in tags:
self.databytecounts = tags['TileByteCounts'].value
elif 'StripByteCounts' in tags:
self.databytecounts = tags['StripByteCounts'].value
elif self.compression == 1:
self.databytecounts = (
product(self.shape) * (self.bitspersample // 8),)
else:
raise ValueError("ByteCounts not found")
assert len(self.shape) == len(self.axes)
def asarray(self, out=None, squeeze=True, lock=None, reopen=True,
maxsize=64*2**30, validate=True):
"""Read image data from file and return as numpy array.
Raise ValueError if format is unsupported.
Parameters
----------
out : numpy.ndarray, str, or file-like object; optional
Buffer where image data will be saved.
If numpy.ndarray, a writable array of compatible dtype and shape.
If str or open file, the file name or file object used to
create a memory-map to an array stored in a binary file on disk.
squeeze : bool
If True, all length-1 dimensions (except X and Y) are
squeezed out from the array.
If False, the shape of the returned array might be different from
the page.shape.
lock : {RLock, NullContext}
A reentrant lock used to syncronize reads from file.
If None (default), the lock of the parent's filehandle is used.
reopen : bool
If True (default) and the parent file handle is closed, the file
is temporarily re-opened and closed if no exception occurs.
maxsize: int or None
Maximum size of data before a ValueError is raised.
Can be used to catch DOS. Default: 64 GB.
validate : bool
If True (default), validate various parameters.
If None, only validate parameters and return None.
"""
self_ = self
self = self.keyframe # self or keyframe
if not self._shape or product(self._shape) == 0:
return
tags = self.tags
if validate or validate is None:
if maxsize and product(self._shape) > maxsize:
raise ValueError("data is too large %s" % str(self._shape))
if self.dtype is None:
raise ValueError("data type not supported: %s%i" % (
self.sampleformat, self.bitspersample))
if self.compression not in TIFF.DECOMPESSORS:
raise ValueError(
"can not decompress %s" % self.compression.name)
if 'SampleFormat' in tags:
tag = tags['SampleFormat']
if tag.count != 1 and any((i-tag.value[0] for i in tag.value)):
raise ValueError(
"sample formats do not match %s" % tag.value)
if self.is_chroma_subsampled:
# TODO: implement chroma subsampling
raise NotImplementedError("chroma subsampling not supported")
if validate is None:
return
fh = self_.parent.filehandle
lock = fh.lock if lock is None else lock
with lock:
closed = fh.closed
if closed:
if reopen:
fh.open()
else:
raise IOError("file handle is closed")
dtype = self._dtype
shape = self._shape
imagewidth = self.imagewidth
imagelength = self.imagelength
imagedepth = self.imagedepth
bitspersample = self.bitspersample
typecode = self.parent.byteorder + dtype.char
lsb2msb = self.fillorder == 2
offsets, bytecounts = self_.offsets_bytecounts
istiled = self.is_tiled
if istiled:
tilewidth = self.tilewidth
tilelength = self.tilelength
tiledepth = self.tiledepth
tw = (imagewidth + tilewidth - 1) // tilewidth
tl = (imagelength + tilelength - 1) // tilelength
td = (imagedepth + tiledepth - 1) // tiledepth
shape = (shape[0], shape[1],
td*tiledepth, tl*tilelength, tw*tilewidth, shape[-1])
tileshape = (tiledepth, tilelength, tilewidth, shape[-1])
runlen = tilewidth
else:
runlen = imagewidth
if out == 'memmap' and self.is_memmappable:
with lock:
result = fh.memmap_array(typecode, shape, offset=offsets[0])
elif self.is_contiguous:
isnative = self.parent.is_native
if out is not None:
isnative = True
out = create_output(out, shape, dtype)
with lock:
fh.seek(offsets[0])
result = fh.read_array(typecode, product(shape), out=out)
if not isnative:
result = result.astype('=' + dtype.char)
if lsb2msb:
reverse_bitorder(result)
else:
result = create_output(out, shape, dtype)
if self.planarconfig == 1:
runlen *= self.samplesperpixel
if bitspersample in (8, 16, 32, 64, 128):
if (bitspersample * runlen) % 8:
raise ValueError("data and sample size mismatch")
def unpack(x, typecode=typecode):
if self.predictor == 3: # PREDICTOR.FLOATINGPOINT
# the floating point horizontal differencing decoder
# needs the raw byte order
typecode = dtype.char
try:
return numpy.fromstring(x, typecode)
except ValueError as e:
# strips may be missing EOI
# warnings.warn("unpack: %s" % e)
xlen = ((len(x) // (bitspersample // 8)) *
(bitspersample // 8))
return numpy.fromstring(x[:xlen], typecode)
elif isinstance(bitspersample, tuple):
def unpack(x):
return unpack_rgb(x, typecode, bitspersample)
else:
def unpack(x):
return unpack_ints(x, typecode, bitspersample, runlen)
decompress = TIFF.DECOMPESSORS[self.compression]
if self.compression == 7: # COMPRESSION.JPEG
if 'JPEGTables' in tags:
table = tags['JPEGTables'].value
else:
table = b''
def decompress(x):
return decode_jpeg(x, table, self.photometric)
if istiled:
tw, tl, td, pl = 0, 0, 0, 0
for tile in buffered_read(fh, lock, offsets, bytecounts):
if lsb2msb:
tile = reverse_bitorder(tile)
tile = decompress(tile)
tile = unpack(tile)
try:
tile.shape = tileshape
except ValueError:
# incomplete tiles; see gdal issue #1179
warnings.warn("invalid tile data")
t = numpy.zeros(tileshape, dtype).reshape(-1)
s = min(tile.size, t.size)
t[:s] = tile[:s]
tile = t.reshape(tileshape)
if self.predictor == 2: # PREDICTOR.HORIZONTAL
numpy.cumsum(tile, axis=-2, dtype=dtype, out=tile)
elif self.predictor == 3: # PREDICTOR.FLOATINGPOINT
raise NotImplementedError()
result[0, pl, td:td+tiledepth,
tl:tl+tilelength, tw:tw+tilewidth, :] = tile
del tile
tw += tilewidth
if tw >= shape[4]:
tw, tl = 0, tl + tilelength
if tl >= shape[3]:
tl, td = 0, td + tiledepth
if td >= shape[2]:
td, pl = 0, pl + 1
result = result[...,
:imagedepth, :imagelength, :imagewidth, :]
else:
strip_size = self.rowsperstrip * self.imagewidth
if self.planarconfig == 1:
strip_size *= self.samplesperpixel
result = result.reshape(-1)
index = 0
for strip in buffered_read(fh, lock, offsets, bytecounts):
if lsb2msb:
strip = reverse_bitorder(strip)
strip = decompress(strip)
strip = unpack(strip)
size = min(result.size, strip.size, strip_size,
result.size - index)
result[index:index+size] = strip[:size]
del strip
index += size
result.shape = self._shape
if self.predictor != 1 and not (istiled and not self.is_contiguous):
if self.parent.is_lsm and self.compression == 1:
pass # work around bug in LSM510 software
elif self.predictor == 2: # PREDICTOR.HORIZONTAL
numpy.cumsum(result, axis=-2, dtype=dtype, out=result)
elif self.predictor == 3: # PREDICTOR.FLOATINGPOINT
result = decode_floats(result)
if squeeze:
try:
result.shape = self.shape
except ValueError:
warnings.warn("failed to reshape from %s to %s" % (
str(result.shape), str(self.shape)))
if closed:
# TODO: file should remain open if an exception occurred above
fh.close()
return result
def asrgb(self, uint8=False, alpha=None, colormap=None,
dmin=None, dmax=None, *args, **kwargs):
"""Return image data as RGB(A).
Work in progress.
"""
data = self.asarray(*args, **kwargs)
self = self.keyframe # self or keyframe
photometric = self.photometric
PHOTOMETRIC = TIFF.PHOTOMETRIC
if photometric == PHOTOMETRIC.PALETTE:
colormap = self.colormap
if (colormap.shape[1] < 2**self.bitspersample or
self.dtype.char not in 'BH'):
raise ValueError("can not apply colormap")
if uint8:
if colormap.max() > 255:
colormap >>= 8
colormap = colormap.astype('uint8')
if 'S' in self.axes:
data = data[..., 0] if self.planarconfig == 1 else data[0]
data = apply_colormap(data, colormap)
elif photometric == PHOTOMETRIC.RGB:
if 'ExtraSamples' in self.tags:
if alpha is None:
alpha = TIFF.EXTRASAMPLE
extrasamples = self.extrasamples
if self.tags['ExtraSamples'].count == 1:
extrasamples = (extrasamples,)
for i, exs in enumerate(extrasamples):
if exs in alpha:
if self.planarconfig == 1:
data = data[..., [0, 1, 2, 3+i]]
else:
data = data[:, [0, 1, 2, 3+i]]
break
else:
if self.planarconfig == 1:
data = data[..., :3]
else:
data = data[:, :3]
# TODO: convert to uint8
elif photometric == PHOTOMETRIC.MINISBLACK:
raise NotImplementedError()
elif photometric == PHOTOMETRIC.MINISWHITE:
raise NotImplementedError()
elif photometric == PHOTOMETRIC.SEPARATED:
raise NotImplementedError()
else:
raise NotImplementedError()
return data
def aspage(self):
return self
@property
def keyframe(self):
return self
@keyframe.setter
def keyframe(self, index):
return
@lazyattr
def offsets_bytecounts(self):
"""Return simplified offsets and bytecounts."""
if self.is_contiguous:
offset, byte_count = self.is_contiguous
return [offset], [byte_count]
return clean_offsets_counts(self.dataoffsets, self.databytecounts)
@lazyattr
def is_contiguous(self):
"""Return offset and size of contiguous data, else None.
Excludes prediction and fill_order.
"""
if (self.compression != 1
or self.bitspersample not in (8, 16, 32, 64)):
return
if 'TileWidth' in self.tags:
if (self.imagewidth != self.tilewidth or
self.imagelength % self.tilelength or
self.tilewidth % 16 or self.tilelength % 16):
return
if ('ImageDepth' in self.tags and 'TileDepth' in self.tags and
(self.imagelength != self.tilelength or
self.imagedepth % self.tiledepth)):
return
offsets = self.dataoffsets
bytecounts = self.databytecounts
if len(offsets) == 1:
return offsets[0], bytecounts[0]
if self.is_stk or all((offsets[i] + bytecounts[i] == offsets[i+1] or
bytecounts[i+1] == 0) # no data/ignore offset
for i in range(len(offsets)-1)):
return offsets[0], sum(bytecounts)
@lazyattr
def is_final(self):
"""Return if page's image data is stored in final form.
Excludes byte-swapping.
"""
return (self.is_contiguous and self.fillorder == 1 and
self.predictor == 1 and not self.is_chroma_subsampled)
@lazyattr
def is_memmappable(self):
"""Return if page's image data in file can be memory-mapped."""
return (self.parent.filehandle.is_file and self.is_final and
(self.bitspersample == 8 or self.parent.is_native) and
self.is_contiguous[0] % self.dtype.itemsize == 0)
def __str__(self, detail=0):
"""Return string containing information about page."""
if self.keyframe != self:
return TiffFrame.__str__(self, detail)
attr = ''
for name in ('memmappable', 'final', 'contiguous'):
attr = getattr(self, 'is_'+name)
if attr:
attr = name.upper()
break
info = ' '.join(s for s in (
'x'.join(str(i) for i in self.shape),
'%s%s' % (TIFF.SAMPLEFORMAT(self.sampleformat).name,
self.bitspersample),
'|'.join(i for i in (
TIFF.PHOTOMETRIC(self.photometric).name,
'TILED' if self.is_tiled else '',
self.compression.name if self.compression != 1 else '',
self.planarconfig.name if self.planarconfig != 1 else '',
self.predictor.name if self.predictor != 1 else '',
self.fillorder.name if self.fillorder != 1 else '')
if i),
attr,
'|'.join((f.upper() for f in self.flags))
) if s)
info = "TiffPage %i @%i %s" % (self.index, self.offset, info)
if detail <= 0:
return info
info = [info]
tags = self.tags
tlines = []
vlines = []
for tag in sorted(tags.values(), key=lambda x: x.code):
value = tag.__str__()
tlines.append(value[:TIFF.PRINT_LINE_WIDTH].lstrip())
if detail > 1 and len(value) > TIFF.PRINT_LINE_WIDTH:
vlines.append("%s\n%s" % (tag.name.upper(),
pformat(tag.value)))
info.append('\n'.join(tlines))
if detail > 1:
info.append('\n\n'.join(vlines))
return '\n\n'.join(info)
@lazyattr
def flags(self):
"""Return set of flags."""
return set((name.lower() for name in sorted(TIFF.FILE_FLAGS)
if getattr(self, 'is_' + name)))
@property
def ndim(self):
"""Return number of array dimensions."""
return len(self.shape)
@property
def size(self):
"""Return number of elements in array."""
return product(self.shape)
@lazyattr
def andor_tags(self):
"""Return consolidated metadata from Andor tags as dict.
Remove Andor tags from self.tags.
"""
if not self.is_andor:
return
tags = self.tags
result = {'Id': tags['AndorId'].value}
for tag in list(self.tags.values()):
code = tag.code
if not 4864 < code < 5031:
continue
value = tag.value
name = tag.name[5:] if len(tag.name) > 5 else tag.name
result[name] = value
del tags[tag.name]
return result
@lazyattr
def epics_tags(self):
"""Return consolidated metadata from EPICS areaDetector tags as dict.
Remove areaDetector tags from self.tags.
"""
# TODO: obtain test file
if not self.is_epics:
return
result = {}
tags = self.tags
for tag in list(self.tags.values()):
code = tag.code
if not 65000 < code < 65500:
continue
value = tag.value
if code == 65000:
result['timeStamp'] = float(value)
elif code == 65001:
result['uniqueID'] = int(value)
elif code == 65002:
result['epicsTS'] = int(value)
elif code == 65003:
result['epicsTS'] = int(value)
else:
key, value = value.split(':')
result[key] = astype(value)
del tags[tag.name]
return result
@property
def is_tiled(self):
"""Page contains tiled image."""
return 'TileWidth' in self.tags
@property
def is_reduced(self):
"""Page is reduced image of another image."""
return ('NewSubfileType' in self.tags and
self.tags['NewSubfileType'].value & 1)
@property
def is_chroma_subsampled(self):
"""Page contains chroma subsampled image."""
return ('YCbCrSubSampling' in self.tags and
self.tags['YCbCrSubSampling'].value != (1, 1))
@lazyattr
def is_imagej(self):
"""Return ImageJ description if exists, else None."""
for description in (self.description, self.description1):
if not description:
return
if description[:7] == 'ImageJ=':
return description
@lazyattr
def is_shaped(self):
"""Return description containing array shape if exists, else None."""
for description in (self.description, self.description1):
if not description:
return
if description[:1] == '{' and '"shape":' in description:
return description
if description[:6] == 'shape=':
return description
@property
def is_mdgel(self):
"""Page contains MDFileTag tag."""
return 'MDFileTag' in self.tags
@property
def is_mediacy(self):
"""Page contains Media Cybernetics Id tag."""
return ('MC_Id' in self.tags and
self.tags['MC_Id'].value[:7] == b'MC TIFF')
@property
def is_stk(self):
"""Page contains UIC2Tag tag."""
return 'UIC2tag' in self.tags
@property
def is_lsm(self):
"""Page contains CZ_LSMINFO tag."""
return 'CZ_LSMINFO' in self.tags
@property
def is_fluoview(self):
"""Page contains FluoView MM_STAMP tag."""
return 'MM_Stamp' in self.tags
@property
def is_nih(self):
"""Page contains NIH image header."""
return 'NIHImageHeader' in self.tags
@property
def is_sgi(self):
"""Page contains SGI image and tile depth tags."""
return 'ImageDepth' in self.tags and 'TileDepth' in self.tags
@property
def is_vista(self):
"""Software tag is 'ISS Vista'."""
return self.software == 'ISS Vista'
@property
def is_metaseries(self):
"""Page contains MDS MetaSeries metadata in ImageDescription tag."""
if self.index > 1 or self.software != 'MetaSeries':
return False
d = self.description
return d.startswith('<MetaData>') and d.endswith('</MetaData>')
@property
def is_ome(self):
"""Page contains OME-XML in ImageDescription tag."""
if self.index > 1 or not self.description:
return False
d = self.description
return d[:14] == '<?xml version=' and d[-6:] == '</OME>'
@property
def is_scn(self):
"""Page contains Leica SCN XML in ImageDescription tag."""
if self.index > 1 or not self.description:
return False
d = self.description
return d[:14] == '<?xml version=' and d[-6:] == '</scn>'
@property
def is_micromanager(self):
"""Page contains Micro-Manager metadata."""
return 'MicroManagerMetadata' in self.tags
@property
def is_andor(self):
"""Page contains Andor Technology tags."""
return 'AndorId' in self.tags
@property
def is_pilatus(self):
"""Page contains Pilatus tags."""
return (self.software[:8] == 'TVX TIFF' and
self.description[:2] == '# ')
@property
def is_epics(self):
"""Page contains EPICS areaDetector tags."""
return self.description == 'EPICS areaDetector'
@property
def is_tvips(self):
"""Page contains TVIPS metadata."""
return 'TVIPS' in self.tags
@property
def is_fei(self):
"""Page contains SFEG or HELIOS metadata."""
return 'FEI_SFEG' in self.tags or 'FEI_HELIOS' in self.tags
@property
def is_sem(self):
"""Page contains Zeiss SEM metadata."""
return 'CZ_SEM' in self.tags
@property
def is_svs(self):
"""Page contains Aperio metadata."""
return self.description[:20] == 'Aperio Image Library'
@property
def is_scanimage(self):
"""Page contains ScanImage metadata."""
return (self.description[:12] == 'state.config' or
self.software[:22] == 'SI.LINE_FORMAT_VERSION')
class TiffFrame(object):
"""Lightweight TIFF image file directory (IFD).
Only a limited number of tag values are read from file, e.g. StripOffsets,
and StripByteCounts. Other tag values are assumed to be identical with a
specified TiffPage instance, the keyframe.
This is intended to reduce resource usage and speed up reading data from
file, not for introspection of metadata.
Not compatible with Python 2.
"""
__slots__ = ('keyframe', 'parent', 'index', 'offset',
'dataoffsets', 'databytecounts')
is_mdgel = False
tags = {}
def __init__(self, parent, index, keyframe):
"""Read specified tags from file.
The file handle position must be at the offset to a valid IFD.
"""
self.keyframe = keyframe
self.parent = parent
self.index = index
unpack = struct.unpack
fh = parent.filehandle
self.offset = fh.tell()
try:
tagno = unpack(parent.tagnoformat, fh.read(parent.tagnosize))[0]
if tagno > 4096:
raise ValueError("suspicious number of tags")
except Exception:
raise ValueError("corrupted page list at offset %i" % self.offset)
# tags = {}
tagcodes = {273, 279, 324, 325} # TIFF.FRAME_TAGS
tagsize = parent.tagsize
codeformat = parent.tagformat1[:2]
data = fh.read(tagsize * tagno)
index = -tagsize
for _ in range(tagno):
index += tagsize
code = unpack(codeformat, data[index:index+2])[0]
if code not in tagcodes:
continue
try:
tag = TiffTag(parent, data[index:index+tagsize])
except TiffTag.Error as e:
warnings.warn(str(e))
continue
if code == 273 or code == 324:
setattr(self, 'dataoffsets', tag.value)
elif code == 279 or code == 325:
setattr(self, 'databytecounts', tag.value)
# elif code == 270:
# tagname = tag.name
# if tagname not in tags:
# tags[tagname] = bytes2str(tag.value)
# elif 'ImageDescription1' not in tags:
# tags['ImageDescription1'] = bytes2str(tag.value)
# else:
# tags[tag.name] = tag.value
def aspage(self):
"""Return TiffPage from file."""
self.parent.filehandle.seek(self.offset)
return TiffPage(self.parent, index=self.index, keyframe=None)
def asarray(self, *args, **kwargs):
"""Read image data from file and return as numpy array."""
# TODO: fix TypeError on Python 2
# "TypeError: unbound method asarray() must be called with TiffPage
# instance as first argument (got TiffFrame instance instead)"
kwargs['validate'] = False
return TiffPage.asarray(self, *args, **kwargs)
def asrgb(self, *args, **kwargs):
"""Read image data from file and return RGB image as numpy array."""
kwargs['validate'] = False
return TiffPage.asrgb(self, *args, **kwargs)
@property
def offsets_bytecounts(self):
"""Return simplified offsets and bytecounts."""
if self.keyframe.is_contiguous:
return self.dataoffsets[:1], self.keyframe.is_contiguous[1:]
return clean_offsets_counts(self.dataoffsets, self.databytecounts)
@property
def is_contiguous(self):
"""Return offset and size of contiguous data, else None."""
if self.keyframe.is_contiguous:
return self.dataoffsets[0], self.keyframe.is_contiguous[1]
@property
def is_memmappable(self):
"""Return if page's image data in file can be memory-mapped."""
return self.keyframe.is_memmappable
def __getattr__(self, name):
"""Return attribute from keyframe."""
if name in TIFF.FRAME_ATTRS:
return getattr(self.keyframe, name)
raise AttributeError("'%s' object has no attribute '%s'" %
(self.__class__.__name__, name))
def __str__(self, detail=0):
"""Return string containing information about frame."""
info = ' '.join(s for s in (
'x'.join(str(i) for i in self.shape),
str(self.dtype)))
return "TiffFrame %i @%i %s" % (self.index, self.offset, info)
class TiffTag(object):
"""TIFF tag structure.
Attributes
----------
name : string
Name of tag.
code : int
Decimal code of tag.
dtype : str
Datatype of tag data. One of TIFF DATA_FORMATS.
count : int
Number of values.
value : various types
Tag data as Python object.
valueoffset : int
Location of value in file.
All attributes are read-only.
"""
__slots__ = ('code', 'count', 'dtype', 'value', 'valueoffset')
class Error(Exception):
pass
def __init__(self, parent, tagheader, **kwargs):
"""Initialize instance from tag header."""
fh = parent.filehandle
byteorder = parent.byteorder
unpack = struct.unpack
offsetsize = parent.offsetsize
self.valueoffset = fh.tell() + offsetsize + 4
code, dtype = unpack(parent.tagformat1, tagheader[:4])
count, value = unpack(parent.tagformat2, tagheader[4:])
try:
dtype = TIFF.DATA_FORMATS[dtype]
except KeyError:
raise TiffTag.Error("unknown tag data type %i" % dtype)
fmt = '%s%i%s' % (byteorder, count * int(dtype[0]), dtype[1])
size = struct.calcsize(fmt)
if size > offsetsize or code in TIFF.TAG_READERS:
self.valueoffset = offset = unpack(parent.offsetformat, value)[0]
if offset < 8 or offset > fh.size - size:
raise TiffTag.Error("invalid tag value offset")
# if offset % 2:
# warnings.warn("tag value does not begin on word boundary")
fh.seek(offset)
if code in TIFF.TAG_READERS:
readfunc = TIFF.TAG_READERS[code]
value = readfunc(fh, byteorder, dtype, count, offsetsize)
elif code in TIFF.TAGS or dtype[-1] == 's':
value = unpack(fmt, fh.read(size))
else:
value = read_numpy(fh, byteorder, dtype, count, offsetsize)
else:
value = unpack(fmt, value[:size])
process = code not in TIFF.TAG_READERS and code not in TIFF.TAG_TUPLE
if process and dtype[-1] == 's' and isinstance(value[0], bytes):
# TIFF ASCII fields can contain multiple strings,
# each terminated with a NUL
value = bytes2str(stripascii(value[0]).strip())
else:
if code in TIFF.TAG_ENUM:
t = TIFF.TAG_ENUM[code]
try:
value = tuple(t(v) for v in value)
except ValueError as e:
warnings.warn(str(e))
if process:
if len(value) == 1:
value = value[0]
self.code = code
self.dtype = dtype
self.count = count
self.value = value
@property
def name(self):
return TIFF.TAGS.get(self.code, str(self.code))
def _fix_lsm_bitspersample(self, parent):
"""Correct LSM bitspersample tag.
Old LSM writers may use a separate region for two 16-bit values,
although they fit into the tag value element of the tag.
"""
if self.code == 258 and self.count == 2:
# TODO: test this case; need example file
warnings.warn("correcting LSM bitspersample tag")
tof = parent.offsetformat[parent.offsetsize]
self.valueoffset = struct.unpack(tof, self._value)[0]
parent.filehandle.seek(self.valueoffset)
self.value = struct.unpack("<HH", parent.filehandle.read(4))
def __str__(self):
"""Return string containing information about tag."""
if self.code in TIFF.TAG_ENUM:
if self.count == 1:
value = TIFF.TAG_ENUM[self.code](self.value).name
else:
value = tuple(v.name for v in self.value)
elif isinstance(self.value, unicode):
value = pformat(self.value)
value = value.replace(u'\n', u'\\n').replace(u'\r', u'')
value = u'"%s"' % value
else:
value = pformat(self.value, linewidth=False, maxlines=2)
value = str(value).split('\n', 1)[0]
tcode = "%i%s" % (self.count * int(self.dtype[0]), self.dtype[1])
line = "TiffTag %i %s %s @%i %s" % (
self.code, self.name, tcode, self.valueoffset, value)
return line
class TiffPageSeries(object):
"""Series of TIFF pages with compatible shape and data type.
Attributes
----------
pages : list of TiffPage
Sequence of TiffPages in series.
dtype : numpy.dtype or str
Data type of the image array in series.
shape : tuple
Dimensions of the image array in series.
axes : str
Labels of axes in shape. See TiffPage.axes.
offset : int or None
Position of image data in file if memory-mappable, else None.
"""
def __init__(self, pages, shape, dtype, axes,
parent=None, name=None, transform=None, stype=None):
"""Initialize instance."""
self.index = 0
self.pages = pages
self.shape = tuple(shape)
self.axes = ''.join(axes)
self.dtype = numpy.dtype(dtype)
self.stype = stype if stype else ''
self.name = name if name else ''
self.transform = transform
if parent:
self.parent = parent
elif pages:
self.parent = pages[0].parent
else:
self.parent = None
def asarray(self, out=None):
"""Return image data from series of TIFF pages as numpy array."""
if self.parent:
result = self.parent.asarray(series=self, out=out)
if self.transform is not None:
result = self.transform(result)
return result
@lazyattr
def offset(self):
"""Return offset to series data in file, if any."""
if not self.pages:
return
pos = 0
for page in self.pages:
if page is None:
return
if not page.is_final:
return
if not pos:
pos = page.is_contiguous[0] + page.is_contiguous[1]
continue
if pos != page.is_contiguous[0]:
return
pos += page.is_contiguous[1]
page = self.pages[0]
offset = page.is_contiguous[0]
if (page.is_imagej or page.is_shaped) and len(self.pages) == 1:
# truncated files
return offset
if pos == offset + product(self.shape) * self.dtype.itemsize:
return offset
@property
def ndim(self):
"""Return number of array dimensions."""
return len(self.shape)
@property
def size(self):
"""Return number of elements in array."""
return int(product(self.shape))
def __len__(self):
"""Return number of TiffPages in series."""
return len(self.pages)
def __getitem__(self, key):
"""Return specified TiffPage."""
return self.pages[key]
def __iter__(self):
"""Return iterator over TiffPages in series."""
return iter(self.pages)
def __str__(self):
"""Return string with information about series."""
s = ' '.join(s for s in (
snipstr("'%s'" % self.name, 20) if self.name else '',
'x'.join(str(i) for i in self.shape),
str(self.dtype),
self.axes,
self.stype,
'%i Pages' % len(self.pages),
('Offset=%i' % self.offset) if self.offset else '') if s)
return 'TiffPageSeries %i %s' % (self.index, s)
class TiffSequence(object):
"""Sequence of TIFF files.
The image data in all files must match shape, dtype, etc.
Attributes
----------
files : list
List of file names.
shape : tuple
Shape of image sequence. Excludes shape of image array.
axes : str
Labels of axes in shape.
Examples
--------
>>> # read image stack from sequence of TIFF files
>>> imsave('temp_C001T001.tif', numpy.random.rand(64, 64))
>>> imsave('temp_C001T002.tif', numpy.random.rand(64, 64))
>>> tifs = TiffSequence("temp_C001*.tif")
>>> tifs.shape
(1, 2)
>>> tifs.axes
'CT'
>>> data = tifs.asarray()
>>> data.shape
(1, 2, 64, 64)
"""
_patterns = {
'axes': r"""
# matches Olympus OIF and Leica TIFF series
_?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))
_?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
_?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
_?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
_?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
_?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
_?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
"""}
class ParseError(Exception):
pass
def __init__(self, files, imread=TiffFile, pattern='axes',
*args, **kwargs):
"""Initialize instance from multiple files.
Parameters
----------
files : str, or sequence of str
Glob pattern or sequence of file names.
Binary streams are not supported.
imread : function or class
Image read function or class with asarray function returning numpy
array from single file.
pattern : str
Regular expression pattern that matches axes names and sequence
indices in file names.
By default, this matches Olympus OIF and Leica TIFF series.
"""
if isinstance(files, basestring):
files = natural_sorted(glob.glob(files))
files = list(files)
if not files:
raise ValueError("no files found")
if not isinstance(files[0], basestring):
raise ValueError("not a file name")
self.files = files
if hasattr(imread, 'asarray'):
# redefine imread
_imread = imread
def imread(fname, *args, **kwargs):
with _imread(fname) as im:
return im.asarray(*args, **kwargs)
self.imread = imread
self.pattern = self._patterns.get(pattern, pattern)
try:
self._parse()
if not self.axes:
self.axes = 'I'
except self.ParseError:
self.axes = 'I'
self.shape = (len(files),)
self._startindex = (0,)
self._indices = tuple((i,) for i in range(len(files)))
def __str__(self):
"""Return string with information about image sequence."""
return "\n".join([
self.files[0],
' size: %i' % len(self.files),
' axes: %s' % self.axes,
' shape: %s' % str(self.shape)])
def __len__(self):
return len(self.files)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def close(self):
pass
def asarray(self, out=None, *args, **kwargs):
"""Read image data from all files and return as numpy array.
The args and kwargs parameters are passed to the imread function.
Raise IndexError or ValueError if image shapes do not match.
"""
im = self.imread(self.files[0], *args, **kwargs)
shape = self.shape + im.shape
result = create_output(out, shape, dtype=im.dtype)
result = result.reshape(-1, *im.shape)
for index, fname in zip(self._indices, self.files):
index = [i-j for i, j in zip(index, self._startindex)]
index = numpy.ravel_multi_index(index, self.shape)
im = self.imread(fname, *args, **kwargs)
result[index] = im
result.shape = shape
return result
def _parse(self):
"""Get axes and shape from file names."""
if not self.pattern:
raise self.ParseError("invalid pattern")
pattern = re.compile(self.pattern, re.IGNORECASE | re.VERBOSE)
matches = pattern.findall(self.files[0])
if not matches:
raise self.ParseError("pattern does not match file names")
matches = matches[-1]
if len(matches) % 2:
raise self.ParseError("pattern does not match axis name and index")
axes = ''.join(m for m in matches[::2] if m)
if not axes:
raise self.ParseError("pattern does not match file names")
indices = []
for fname in self.files:
matches = pattern.findall(fname)[-1]
if axes != ''.join(m for m in matches[::2] if m):
raise ValueError("axes do not match within the image sequence")
indices.append([int(m) for m in matches[1::2] if m])
shape = tuple(numpy.max(indices, axis=0))
startindex = tuple(numpy.min(indices, axis=0))
shape = tuple(i-j+1 for i, j in zip(shape, startindex))
if product(shape) != len(self.files):
warnings.warn("files are missing. Missing data are zeroed")
self.axes = axes.upper()
self.shape = shape
self._indices = indices
self._startindex = startindex
class FileHandle(object):
"""Binary file handle.
A limited, special purpose file handler that can:
* handle embedded files (for CZI within CZI files)
* re-open closed files (for multi file formats, such as OME-TIFF)
* read and write numpy arrays and records from file like objects
Only 'rb' and 'wb' modes are supported. Concurrently reading and writing
of the same stream is untested.
When initialized from another file handle, do not use it unless this
FileHandle is closed.
Attributes
----------
name : str
Name of the file.
path : str
Absolute path to file.
size : int
Size of file in bytes.
is_file : bool
If True, file has a filno and can be memory-mapped.
All attributes are read-only.
"""
__slots__ = ('_fh', '_file', '_mode', '_name', '_dir', '_lock',
'_offset', '_size', '_close', 'is_file')
def __init__(self, file, mode='rb', name=None, offset=None, size=None):
"""Initialize file handle from file name or another file handle.
Parameters
----------
file : str, binary stream, or FileHandle
File name or seekable binary stream, such as a open file
or BytesIO.
mode : str
File open mode in case 'file' is a file name. Must be 'rb' or 'wb'.
name : str
Optional name of file in case 'file' is a binary stream.
offset : int
Optional start position of embedded file. By default, this is
the current file position.
size : int
Optional size of embedded file. By default, this is the number
of bytes from the 'offset' to the end of the file.
"""
self._fh = None
self._file = file
self._mode = mode
self._name = name
self._dir = ''
self._offset = offset
self._size = size
self._close = True
self.is_file = False
self._lock = NullContext()
self.open()
def open(self):
"""Open or re-open file."""
if self._fh:
return # file is open
if isinstance(self._file, basestring):
# file name
self._file = os.path.realpath(self._file)
self._dir, self._name = os.path.split(self._file)
self._fh = open(self._file, self._mode)
self._close = True
if self._offset is None:
self._offset = 0
elif isinstance(self._file, FileHandle):
# FileHandle
self._fh = self._file._fh
if self._offset is None:
self._offset = 0
self._offset += self._file._offset
self._close = False
if not self._name:
if self._offset:
name, ext = os.path.splitext(self._file._name)
self._name = "%s@%i%s" % (name, self._offset, ext)
else:
self._name = self._file._name
if self._mode and self._mode != self._file._mode:
raise ValueError('FileHandle has wrong mode')
self._mode = self._file._mode
self._dir = self._file._dir
elif hasattr(self._file, 'seek'):
# binary stream: open file, BytesIO
try:
self._file.tell()
except Exception:
raise ValueError("binary stream is not seekable")
self._fh = self._file
if self._offset is None:
self._offset = self._file.tell()
self._close = False
if not self._name:
try:
self._dir, self._name = os.path.split(self._fh.name)
except AttributeError:
self._name = "Unnamed binary stream"
try:
self._mode = self._fh.mode
except AttributeError:
pass
else:
raise ValueError("The first parameter must be a file name, "
"seekable binary stream, or FileHandle")
if self._offset:
self._fh.seek(self._offset)
if self._size is None:
pos = self._fh.tell()
self._fh.seek(self._offset, 2)
self._size = self._fh.tell()
self._fh.seek(pos)
try:
self._fh.fileno()
self.is_file = True
except Exception:
self.is_file = False
def read(self, size=-1):
"""Read 'size' bytes from file, or until EOF is reached."""
if size < 0 and self._offset:
size = self._size
return self._fh.read(size)
def write(self, bytestring):
"""Write bytestring to file."""
return self._fh.write(bytestring)
def flush(self):
"""Flush write buffers if applicable."""
return self._fh.flush()
def memmap_array(self, dtype, shape, offset=0, mode='r', order='C'):
"""Return numpy.memmap of data stored in file."""
if not self.is_file:
raise ValueError("Can not memory-map file without fileno")
return numpy.memmap(self._fh, dtype=dtype, mode=mode,
offset=self._offset + offset,
shape=shape, order=order)
def read_array(self, dtype, count=-1, sep="", chunksize=2**25, out=None):
"""Return numpy array from file.
Work around numpy issue #2230, "numpy.fromfile does not accept
StringIO object" https://github.com/numpy/numpy/issues/2230.
"""
fh = self._fh
dtype = numpy.dtype(dtype)
size = self._size if count < 0 else count * dtype.itemsize
if out is None:
try:
return numpy.fromfile(fh, dtype, count, sep)
except IOError:
# ByteIO
data = fh.read(size)
return numpy.fromstring(data, dtype, count, sep)
# Read data from file in chunks and copy to output array
shape = out.shape
size = min(out.nbytes, size)
out = out.reshape(-1)
index = 0
while size > 0:
data = fh.read(min(chunksize, size))
datasize = len(data)
if datasize == 0:
break
size -= datasize
data = numpy.fromstring(data, dtype)
out[index:index+data.size] = data
index += data.size
if hasattr(out, 'flush'):
out.flush()
return out.reshape(shape)
def read_record(self, dtype, shape=1, byteorder=None):
"""Return numpy record from file."""
rec = numpy.rec
try:
record = rec.fromfile(self._fh, dtype, shape, byteorder=byteorder)
except Exception:
dtype = numpy.dtype(dtype)
if shape is None:
shape = self._size // dtype.itemsize
size = product(sequence(shape)) * dtype.itemsize
data = self._fh.read(size)
record = rec.fromstring(data, dtype, shape, byteorder=byteorder)
return record[0] if shape == 1 else record
def write_empty(self, size):
"""Append size bytes to file. Position must be at end of file."""
if size < 1:
return
self._fh.seek(size-1, 1)
self._fh.write(b'\x00')
def write_array(self, data):
"""Write numpy array to binary file."""
try:
data.tofile(self._fh)
except Exception:
# BytesIO
self._fh.write(data.tostring())
def tell(self):
"""Return file's current position."""
return self._fh.tell() - self._offset
def seek(self, offset, whence=0):
"""Set file's current position."""
if self._offset:
if whence == 0:
self._fh.seek(self._offset + offset, whence)
return
elif whence == 2 and self._size > 0:
self._fh.seek(self._offset + self._size + offset, 0)
return
self._fh.seek(offset, whence)
def close(self):
"""Close file."""
if self._close and self._fh:
self._fh.close()
self._fh = None
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def __getattr__(self, name):
"""Return attribute from underlying file object."""
if self._offset:
warnings.warn(
"FileHandle: '%s' not implemented for embedded files" % name)
return getattr(self._fh, name)
@property
def name(self):
return self._name
@property
def dirname(self):
return self._dir
@property
def path(self):
return os.path.join(self._dir, self._name)
@property
def size(self):
return self._size
@property
def closed(self):
return self._fh is None
@property
def lock(self):
return self._lock
@lock.setter
def lock(self, value):
self._lock = threading.RLock() if value else NullContext()
class NullContext(object):
"""Null context manager.
>>> with NullContext():
... pass
"""
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
class OpenFileCache(object):
"""Keep files open."""
__slots__ = ('files', 'past', 'lock', 'size')
def __init__(self, size, lock=None):
"""Initialize open file cache."""
self.past = [] # FIFO of opened files
self.files = {} # refcounts of opened files
self.lock = NullContext() if lock is None else lock
self.size = int(size)
def open(self, filehandle):
"""Re-open file if necessary."""
with self.lock:
if filehandle in self.files:
self.files[filehandle] += 1
elif filehandle.closed:
filehandle.open()
self.files[filehandle] = 1
self.past.append(filehandle)
def close(self, filehandle):
"""Close openend file if no longer used."""
with self.lock:
if filehandle in self.files:
self.files[filehandle] -= 1
# trim the file cache
index = 0
size = len(self.past)
while size > self.size and index < size:
filehandle = self.past[index]
if self.files[filehandle] == 0:
filehandle.close()
del self.files[filehandle]
del self.past[index]
size -= 1
else:
index += 1
def clear(self):
"""Close all opened files if not in use."""
with self.lock:
for filehandle, refcount in list(self.files.items()):
if refcount == 0:
filehandle.close()
del self.files[filehandle]
del self.past[self.past.index(filehandle)]
class LazyConst(object):
"""Class whose attributes are computed on first access from its methods."""
def __init__(self, cls):
self._cls = cls
self.__doc__ = getattr(cls, '__doc__')
def __getattr__(self, name):
func = getattr(self._cls, name)
if not callable(func):
return func
try:
value = func()
except TypeError:
# Python 2 unbound method
value = func.__func__()
setattr(self, name, value)
return value
@LazyConst
class TIFF(object):
"""Namespace for module constants."""
def TAGS():
# TIFF tag codes and names
return {
254: 'NewSubfileType',
255: 'SubfileType',
256: 'ImageWidth',
257: 'ImageLength',
258: 'BitsPerSample',
259: 'Compression',
262: 'PhotometricInterpretation',
263: 'Threshholding',
264: 'CellWidth',
265: 'CellLength',
266: 'FillOrder',
269: 'DocumentName',
270: 'ImageDescription',
271: 'Make',
272: 'Model',
273: 'StripOffsets',
274: 'Orientation',
277: 'SamplesPerPixel',
278: 'RowsPerStrip',
279: 'StripByteCounts',
280: 'MinSampleValue',
281: 'MaxSampleValue',
282: 'XResolution',
283: 'YResolution',
284: 'PlanarConfiguration',
285: 'PageName',
286: 'XPosition',
287: 'YPosition',
288: 'FreeOffsets',
289: 'FreeByteCounts',
290: 'GrayResponseUnit',
291: 'GrayResponseCurve',
292: 'T4Options',
293: 'T6Options',
296: 'ResolutionUnit',
297: 'PageNumber',
300: 'ColorResponseUnit',
301: 'TransferFunction',
305: 'Software',
306: 'DateTime',
315: 'Artist',
316: 'HostComputer',
317: 'Predictor',
318: 'WhitePoint',
319: 'PrimaryChromaticities',
320: 'ColorMap',
321: 'HalftoneHints',
322: 'TileWidth',
323: 'TileLength',
324: 'TileOffsets',
325: 'TileByteCounts',
326: 'BadFaxLines',
327: 'CleanFaxData',
328: 'ConsecutiveBadFaxLines',
330: 'SubIFDs',
332: 'InkSet',
333: 'InkNames',
334: 'NumberOfInks',
336: 'DotRange',
337: 'TargetPrinter',
338: 'ExtraSamples',
339: 'SampleFormat',
340: 'SMinSampleValue',
341: 'SMaxSampleValue',
342: 'TransferRange',
343: 'ClipPath',
344: 'XClipPathUnits',
345: 'YClipPathUnits',
346: 'Indexed',
347: 'JPEGTables',
351: 'OPIProxy',
400: 'GlobalParametersIFD',
401: 'ProfileType',
402: 'FaxProfile',
403: 'CodingMethods',
404: 'VersionYear',
405: 'ModeNumber',
433: 'Decode',
434: 'DefaultImageColor',
435: 'T82Options',
512: 'JPEGProc',
513: 'JPEGInterchangeFormat',
514: 'JPEGInterchangeFormatLength',
515: 'JPEGRestartInterval',
517: 'JPEGLosslessPredictors',
518: 'JPEGPointTransforms',
519: 'JPEGQTables',
520: 'JPEGDCTables',
521: 'JPEGACTables',
529: 'YCbCrCoefficients',
530: 'YCbCrSubSampling',
531: 'YCbCrPositioning',
532: 'ReferenceBlackWhite',
559: 'StripRowCounts',
700: 'XMP',
4864: 'AndorId', # TODO: Andor Technology 4864 - 5030
4869: 'AndorTemperature',
4876: 'AndorExposureTime',
4878: 'AndorKineticCycleTime',
4879: 'AndorAccumulations',
4881: 'AndorAcquisitionCycleTime',
4882: 'AndorReadoutTime',
4884: 'AndorPhotonCounting',
4885: 'AndorEmDacLevel',
4890: 'AndorFrames',
4896: 'AndorHorizontalFlip',
4897: 'AndorVerticalFlip',
4898: 'AndorClockwise',
4899: 'AndorCounterClockwise',
4904: 'AndorVerticalClockVoltage',
4905: 'AndorVerticalShiftSpeed',
4907: 'AndorPreAmpSetting',
4908: 'AndorCameraSerial',
4911: 'AndorActualTemperature',
4912: 'AndorBaselineClamp',
4913: 'AndorPrescans',
4914: 'AndorModel',
4915: 'AndorChipSizeX',
4916: 'AndorChipSizeY',
4944: 'AndorBaselineOffset',
4966: 'AndorSoftwareVersion',
# Private tags
32781: 'ImageID',
32932: 'WangAnnotation',
32995: 'Matteing',
32996: 'DataType',
32997: 'ImageDepth',
32998: 'TileDepth',
33300: 'ImageFullWidth',
33301: 'ImageFullLength',
33302: 'TextureFormat',
33303: 'TextureWrapModes',
33304: 'FieldOfViewCotangent',
33305: 'MatrixWorldToScreen',
33306: 'MatrixWorldToCamera',
33421: 'CFARepeatPatternDim',
33422: 'CFAPattern',
33432: 'Copyright',
33445: 'MDFileTag',
33446: 'MDScalePixel',
33447: 'MDColorTable',
33448: 'MDLabName',
33449: 'MDSampleInfo',
33450: 'MDPrepDate',
33451: 'MDPrepTime',
33452: 'MDFileUnits',
33550: 'ModelPixelScaleTag',
33628: 'UIC1tag', # Metamorph Universal Imaging Corp STK
33629: 'UIC2tag',
33630: 'UIC3tag',
33631: 'UIC4tag',
33723: 'IPTC',
33918: 'INGRPacketDataTag',
33919: 'INGRFlagRegisters',
33920: 'IrasBTransformationMatrix',
33922: 'ModelTiepointTag',
34118: 'CZ_SEM', # Zeiss SEM
34122: 'IPLAB', # number of images
34264: 'ModelTransformationTag',
34361: 'MM_Header',
34362: 'MM_Stamp',
34363: 'MM_Unknown',
34377: 'Photoshop',
34386: 'MM_UserBlock',
34412: 'CZ_LSMINFO',
34665: 'ExifIFD',
34675: 'ICCProfile',
34680: 'FEI_SFEG', #
34682: 'FEI_HELIOS', #
34683: 'FEI_TITAN', #
34732: 'ImageLayer',
34735: 'GeoKeyDirectoryTag',
34736: 'GeoDoubleParamsTag',
34737: 'GeoAsciiParamsTag',
34853: 'GPSIFD',
34908: 'HylaFAXFaxRecvParams',
34909: 'HylaFAXFaxSubAddress',
34910: 'HylaFAXFaxRecvTime',
34911: 'FaxDcs',
37439: 'StoNits',
37679: 'MODI_TXT', # Microsoft Office Document Imaging
37681: 'MODI_POS',
37680: 'MODI_OLE',
37706: 'TVIPS', # offset to TemData structure
37707: 'TVIPS1',
37708: 'TVIPS2', # same TemData structure as undefined
37724: 'ImageSourceData',
40001: 'MC_IpWinScal', # Media Cybernetics
40100: 'MC_IdOld',
40965: 'InteroperabilityIFD',
42112: 'GDAL_METADATA',
42113: 'GDAL_NODATA',
43314: 'NIHImageHeader',
50215: 'OceScanjobDescription',
50216: 'OceApplicationSelector',
50217: 'OceIdentificationNumber',
50218: 'OceImageLogicCharacteristics',
50288: 'MC_Id', # Media Cybernetics
50289: 'MC_XYPosition',
50290: 'MC_ZPosition',
50291: 'MC_XYCalibration',
50292: 'MC_LensCharacteristics',
50293: 'MC_ChannelName',
50294: 'MC_ExcitationWavelength',
50295: 'MC_TimeStamp',
50296: 'MC_FrameProperties',
50706: 'DNGVersion',
50707: 'DNGBackwardVersion',
50708: 'UniqueCameraModel',
50709: 'LocalizedCameraModel',
50710: 'CFAPlaneColor',
50711: 'CFALayout',
50712: 'LinearizationTable',
50713: 'BlackLevelRepeatDim',
50714: 'BlackLevel',
50715: 'BlackLevelDeltaH',
50716: 'BlackLevelDeltaV',
50717: 'WhiteLevel',
50718: 'DefaultScale',
50719: 'DefaultCropOrigin',
50720: 'DefaultCropSize',
50721: 'ColorMatrix1',
50722: 'ColorMatrix2',
50723: 'CameraCalibration1',
50724: 'CameraCalibration2',
50725: 'ReductionMatrix1',
50726: 'ReductionMatrix2',
50727: 'AnalogBalance',
50728: 'AsShotNeutral',
50729: 'AsShotWhiteXY',
50730: 'BaselineExposure',
50731: 'BaselineNoise',
50732: 'BaselineSharpness',
50733: 'BayerGreenSplit',
50734: 'LinearResponseLimit',
50735: 'CameraSerialNumber',
50736: 'LensInfo',
50737: 'ChromaBlurRadius',
50738: 'AntiAliasStrength',
50739: 'ShadowScale',
50740: 'DNGPrivateData',
50741: 'MakerNoteSafety',
50778: 'CalibrationIlluminant1',
50779: 'CalibrationIlluminant2',
50780: 'BestQualityScale',
50781: 'RawDataUniqueID',
50784: 'AliasLayerMetadata',
50827: 'OriginalRawFileName',
50828: 'OriginalRawFileData',
50829: 'ActiveArea',
50830: 'MaskedAreas',
50831: 'AsShotICCProfile',
50832: 'AsShotPreProfileMatrix',
50833: 'CurrentICCProfile',
50834: 'CurrentPreProfileMatrix',
50838: 'IJMetadataByteCounts',
50839: 'IJMetadata',
51023: 'FibicsXML', #
51123: 'MicroManagerMetadata',
65200: 'FlexXML', #
65563: 'PerSample',
}
def TAG_NAMES():
return {v: c for c, v in TIFF.TAGS.items()}
def TAG_READERS():
# Map TIFF tag codes to import functions
return {
320: read_colormap,
700: read_bytes, # read_utf8,
34377: read_numpy,
33723: read_bytes,
34675: read_bytes,
33628: read_uic1tag, # Universal Imaging Corp STK
33629: read_uic2tag,
33630: read_uic3tag,
33631: read_uic4tag,
34118: read_cz_sem, # Carl Zeiss SEM
34361: read_mm_header, # Olympus FluoView
34362: read_mm_stamp,
34363: read_numpy, # MM_Unknown
34386: read_numpy, # MM_UserBlock
34412: read_cz_lsminfo, # Carl Zeiss LSM
34680: read_fei_metadata, # S-FEG
34682: read_fei_metadata, # Helios NanoLab
37706: read_tvips_header, # TVIPS EMMENU
43314: read_nih_image_header,
# 40001: read_bytes,
40100: read_bytes,
50288: read_bytes,
50296: read_bytes,
50839: read_bytes,
51123: read_json,
34665: read_exif_ifd,
34853: read_gps_ifd,
40965: read_interoperability_ifd
}
def TAG_TUPLE():
# Tags whose values must be stored as tuples
return frozenset((273, 279, 324, 325, 530, 531))
def TAG_ATTRIBUTES():
# Map tag codes to TiffPage attribute names
return {
'ImageWidth': 'imagewidth',
'ImageLength': 'imagelength',
'BitsPerSample': 'bitspersample',
'Compression': 'compression',
'PlanarConfiguration': 'planarconfig',
'FillOrder': 'fillorder',
'PhotometricInterpretation': 'photometric',
'ColorMap': 'colormap',
'ImageDescription': 'description',
'ImageDescription1': 'description1',
'SamplesPerPixel': 'samplesperpixel',
'RowsPerStrip': 'rowsperstrip',
'Software': 'software',
'Predictor': 'predictor',
'TileWidth': 'tilewidth',
'TileLength': 'tilelength',
'ExtraSamples': 'extrasamples',
'SampleFormat': 'sampleformat',
'ImageDepth': 'imagedepth',
'TileDepth': 'tiledepth',
}
def TAG_ENUM():
return {
# 254: TIFF.FILETYPE,
255: TIFF.OFILETYPE,
259: TIFF.COMPRESSION,
262: TIFF.PHOTOMETRIC,
263: TIFF.THRESHHOLD,
266: TIFF.FILLORDER,
274: TIFF.ORIENTATION,
284: TIFF.PLANARCONFIG,
290: TIFF.GRAYRESPONSEUNIT,
# 292: TIFF.GROUP3OPT,
# 293: TIFF.GROUP4OPT,
296: TIFF.RESUNIT,
300: TIFF.COLORRESPONSEUNIT,
317: TIFF.PREDICTOR,
338: TIFF.EXTRASAMPLE,
339: TIFF.SAMPLEFORMAT,
# 512: TIFF.JPEGPROC,
# 531: TIFF.YCBCRPOSITION,
}
def FILETYPE():
class FILETYPE(enum.IntFlag):
# Python 3.6 only
UNDEFINED = 0
REDUCEDIMAGE = 1
PAGE = 2
MASK = 4
return FILETYPE
def OFILETYPE():
class OFILETYPE(enum.IntEnum):
UNDEFINED = 0
IMAGE = 1
REDUCEDIMAGE = 2
PAGE = 3
return OFILETYPE
def COMPRESSION():
class COMPRESSION(enum.IntEnum):
NONE = 1 # Uncompressed
CCITTRLE = 2 # CCITT 1D
CCITT_T4 = 3 # 'T4/Group 3 Fax',
CCITT_T6 = 4 # 'T6/Group 4 Fax',
LZW = 5
OJPEG = 6 # old-style JPEG
JPEG = 7
ADOBE_DEFLATE = 8
JBIG_BW = 9
JBIG_COLOR = 10
JPEG_99 = 99
KODAK_262 = 262
NEXT = 32766
SONY_ARW = 32767
PACKED_RAW = 32769
SAMSUNG_SRW = 32770
CCIRLEW = 32771
SAMSUNG_SRW2 = 32772
PACKBITS = 32773
THUNDERSCAN = 32809
IT8CTPAD = 32895
IT8LW = 32896
IT8MP = 32897
IT8BL = 32898
PIXARFILM = 32908
PIXARLOG = 32909
DEFLATE = 32946
DCS = 32947
APERIO_JP2000_YCBC = 33003 # Leica Aperio
APERIO_JP2000_RGB = 33005 # Leica Aperio
JBIG = 34661
SGILOG = 34676
SGILOG24 = 34677
JPEG2000 = 34712
NIKON_NEF = 34713
JBIG2 = 34715
MDI_BINARY = 34718 # 'Microsoft Document Imaging
MDI_PROGRESSIVE = 34719 # 'Microsoft Document Imaging
MDI_VECTOR = 34720 # 'Microsoft Document Imaging
JPEG_LOSSY = 34892
LZMA = 34925
OPS_PNG = 34933 # Objective Pathology Services
OPS_JPEGXR = 34934 # Objective Pathology Services
KODAK_DCR = 65000
PENTAX_PEF = 65535
# def __bool__(self): return self != 1 # Python 3.6 only
return COMPRESSION
def PHOTOMETRIC():
class PHOTOMETRIC(enum.IntEnum):
MINISWHITE = 0
MINISBLACK = 1
RGB = 2
PALETTE = 3
MASK = 4
SEPARATED = 5 # CMYK
YCBCR = 6
CIELAB = 8
ICCLAB = 9
ITULAB = 10
CFA = 32803 # Color Filter Array
LOGL = 32844
LOGLUV = 32845
LINEAR_RAW = 34892
return PHOTOMETRIC
def THRESHHOLD():
class THRESHHOLD(enum.IntEnum):
BILEVEL = 1
HALFTONE = 2
ERRORDIFFUSE = 3
return THRESHHOLD
def FILLORDER():
class FILLORDER(enum.IntEnum):
MSB2LSB = 1
LSB2MSB = 2
return FILLORDER
def ORIENTATION():
class ORIENTATION(enum.IntEnum):
TOPLEFT = 1
TOPRIGHT = 2
BOTRIGHT = 3
BOTLEFT = 4
LEFTTOP = 5
RIGHTTOP = 6
RIGHTBOT = 7
LEFTBOT = 8
return ORIENTATION
def PLANARCONFIG():
class PLANARCONFIG(enum.IntEnum):
CONTIG = 1
SEPARATE = 2
return PLANARCONFIG
def GRAYRESPONSEUNIT():
class GRAYRESPONSEUNIT(enum.IntEnum):
_10S = 1
_100S = 2
_1000S = 3
_10000S = 4
_100000S = 5
return GRAYRESPONSEUNIT
def GROUP4OPT():
class GROUP4OPT(enum.IntEnum):
UNCOMPRESSED = 2
return GROUP4OPT
def RESUNIT():
class RESUNIT(enum.IntEnum):
NONE = 1
INCH = 2
CENTIMETER = 3
# def __bool__(self): return self != 1 # Python 3.6 only
return RESUNIT
def COLORRESPONSEUNIT():
class COLORRESPONSEUNIT(enum.IntEnum):
_10S = 1
_100S = 2
_1000S = 3
_10000S = 4
_100000S = 5
return COLORRESPONSEUNIT
def PREDICTOR():
class PREDICTOR(enum.IntEnum):
NONE = 1
HORIZONTAL = 2
FLOATINGPOINT = 3
# def __bool__(self): return self != 1 # Python 3.6 only
return PREDICTOR
def EXTRASAMPLE():
class EXTRASAMPLE(enum.IntEnum):
UNSPECIFIED = 0
ASSOCALPHA = 1
UNASSALPHA = 2
return EXTRASAMPLE
def SAMPLEFORMAT():
class SAMPLEFORMAT(enum.IntEnum):
UINT = 1
INT = 2
IEEEFP = 3
VOID = 4
COMPLEXINT = 5
COMPLEXIEEEFP = 6
return SAMPLEFORMAT
def DATATYPES():
class DATATYPES(enum.IntEnum):
NOTYPE = 0
BYTE = 1
ASCII = 2
SHORT = 3
LONG = 4
RATIONAL = 5
SBYTE = 6
UNDEFINED = 7
SSHORT = 8
SLONG = 9
SRATIONAL = 10
FLOAT = 11
DOUBLE = 12
IFD = 13
UNICODE = 14
COMPLEX = 15
LONG8 = 16
SLONG8 = 17
IFD8 = 18
return DATATYPES
def DATA_FORMATS():
# Map TIFF DATATYPES to Python struct formats
return {
1: '1B', # BYTE 8-bit unsigned integer.
2: '1s', # ASCII 8-bit byte that contains a 7-bit ASCII code;
# the last byte must be NULL (binary zero).
3: '1H', # SHORT 16-bit (2-byte) unsigned integer
4: '1I', # LONG 32-bit (4-byte) unsigned integer.
5: '2I', # RATIONAL Two LONGs: the first represents the numerator
# of a fraction; the second, the denominator.
6: '1b', # SBYTE An 8-bit signed (twos-complement) integer.
7: '1p', # UNDEFINED An 8-bit byte that may contain anything,
# depending on the definition of the field.
8: '1h', # SSHORT A 16-bit (2-byte) signed (twos-complement)
# integer.
9: '1i', # SLONG A 32-bit (4-byte) signed (twos-complement)
# integer.
10: '2i', # SRATIONAL Two SLONGs: the first represents the
# numerator of a fraction, the second the denominator.
11: '1f', # FLOAT Single precision (4-byte) IEEE format.
12: '1d', # DOUBLE Double precision (8-byte) IEEE format.
13: '1I', # IFD unsigned 4 byte IFD offset.
# 14: '', # UNICODE
# 15: '', # COMPLEX
16: '1Q', # LONG8 unsigned 8 byte integer (BigTiff)
17: '1q', # SLONG8 signed 8 byte integer (BigTiff)
18: '1Q', # IFD8 unsigned 8 byte IFD offset (BigTiff)
}
def DATA_DTYPES():
# Map numpy dtypes to TIFF DATATYPES
return {'B': 1, 's': 2, 'H': 3, 'I': 4, '2I': 5, 'b': 6,
'h': 8, 'i': 9, '2i': 10, 'f': 11, 'd': 12, 'Q': 16, 'q': 17}
def SAMPLE_DTYPES():
# Map TIFF SampleFormats and BitsPerSample to numpy dtype
return {
(1, 1): '?', # bitmap
(1, 2): 'B',
(1, 3): 'B',
(1, 4): 'B',
(1, 5): 'B',
(1, 6): 'B',
(1, 7): 'B',
(1, 8): 'B',
(1, 9): 'H',
(1, 10): 'H',
(1, 11): 'H',
(1, 12): 'H',
(1, 13): 'H',
(1, 14): 'H',
(1, 15): 'H',
(1, 16): 'H',
(1, 17): 'I',
(1, 18): 'I',
(1, 19): 'I',
(1, 20): 'I',
(1, 21): 'I',
(1, 22): 'I',
(1, 23): 'I',
(1, 24): 'I',
(1, 25): 'I',
(1, 26): 'I',
(1, 27): 'I',
(1, 28): 'I',
(1, 29): 'I',
(1, 30): 'I',
(1, 31): 'I',
(1, 32): 'I',
(1, 64): 'Q',
(2, 8): 'b',
(2, 16): 'h',
(2, 32): 'i',
(2, 64): 'q',
(3, 16): 'e',
(3, 32): 'f',
(3, 64): 'd',
(6, 64): 'F',
(6, 128): 'D',
(1, (5, 6, 5)): 'B',
}
def DECOMPESSORS():
decompressors = {
None: identityfunc,
1: identityfunc,
5: decode_lzw,
# 7: decode_jpeg,
8: zlib.decompress,
32946: zlib.decompress,
32773: decode_packbits,
}
if lzma:
decompressors[34925] = lzma.decompress
return decompressors
def FRAME_ATTRS():
# Attributes that a TiffFrame shares with its keyframe
return set('shape ndim size dtype axes is_final'.split())
def FILE_FLAGS():
# TiffFile and TiffPage 'is_\*' attributes
exclude = set('reduced final memmappable contiguous '
'chroma_subsampled'.split())
return set(a[3:] for a in dir(TiffPage)
if a[:3] == 'is_' and a[3:] not in exclude)
def FILE_EXTENSIONS():
# TIFF file extensions
return tuple('tif tiff ome.tif lsm stk '
'gel seq svs bif tf8 tf2 btf'.split())
def FILEOPEN_FILTER():
# String for use in Windows File Open box
return [("%s files" % ext.upper(), "*.%s" % ext)
for ext in TIFF.FILE_EXTENSIONS] + [("allfiles", "*")]
def AXES_LABELS():
# TODO: is there a standard for character axes labels?
axes = {
'X': 'width',
'Y': 'height',
'Z': 'depth',
'S': 'sample', # rgb(a)
'I': 'series', # general sequence, plane, page, IFD
'T': 'time',
'C': 'channel', # color, emission wavelength
'A': 'angle',
'P': 'phase', # formerly F # P is Position in LSM!
'R': 'tile', # region, point, mosaic
'H': 'lifetime', # histogram
'E': 'lambda', # excitation wavelength
'L': 'exposure', # lux
'V': 'event',
'Q': 'other',
'M': 'mosaic', # LSM 6
}
axes.update(dict((v, k) for k, v in axes.items()))
return axes
def ANDOR_TAGS():
# Andor Technology tags #4864 - 5030
return set(range(4864, 5030))
def EXIF_TAGS():
return {
33434: 'ExposureTime',
33437: 'FNumber',
34850: 'ExposureProgram',
34852: 'SpectralSensitivity',
34855: 'ISOSpeedRatings',
34856: 'OECF',
34858: 'TimeZoneOffset',
34859: 'SelfTimerMode',
34864: 'SensitivityType',
34865: 'StandardOutputSensitivity',
34866: 'RecommendedExposureIndex',
34867: 'ISOSpeed',
34868: 'ISOSpeedLatitudeyyy',
34869: 'ISOSpeedLatitudezzz',
36864: 'ExifVersion',
36867: 'DateTimeOriginal',
36868: 'DateTimeDigitized',
36873: 'GooglePlusUploadCode',
36880: 'OffsetTime',
36881: 'OffsetTimeOriginal',
36882: 'OffsetTimeDigitized',
37121: 'ComponentsConfiguration',
37122: 'CompressedBitsPerPixel',
37377: 'ShutterSpeedValue',
37378: 'ApertureValue',
37379: 'BrightnessValue',
37380: 'ExposureBiasValue',
37381: 'MaxApertureValue',
37382: 'SubjectDistance',
37383: 'MeteringMode',
37384: 'LightSource',
37385: 'Flash',
37386: 'FocalLength',
37393: 'ImageNumber',
37394: 'SecurityClassification',
37395: 'ImageHistory',
37396: 'SubjectArea',
37500: 'MakerNote',
37510: 'UserComment',
37520: 'SubsecTime',
37521: 'SubsecTimeOriginal',
37522: 'SubsecTimeDigitized',
37888: 'Temperature',
37889: 'Humidity',
37890: 'Pressure',
37891: 'WaterDepth',
37892: 'Acceleration',
37893: 'CameraElevationAngle',
40960: 'FlashpixVersion',
40961: 'ColorSpace',
40962: 'PixelXDimension',
40963: 'PixelYDimension',
40964: 'RelatedSoundFile',
41483: 'FlashEnergy',
41484: 'SpatialFrequencyResponse',
41486: 'FocalPlaneXResolution',
41487: 'FocalPlaneYResolution',
41488: 'FocalPlaneResolutionUnit',
41492: 'SubjectLocation',
41493: 'ExposureIndex',
41495: 'SensingMethod',
41728: 'FileSource',
41729: 'SceneType',
41730: 'CFAPattern',
41985: 'CustomRendered',
41986: 'ExposureMode',
41987: 'WhiteBalance',
41988: 'DigitalZoomRatio',
41989: 'FocalLengthIn35mmFilm',
41990: 'SceneCaptureType',
41991: 'GainControl',
41992: 'Contrast',
41993: 'Saturation',
41994: 'Sharpness',
41995: 'DeviceSettingDescription',
41996: 'SubjectDistanceRange',
42016: 'ImageUniqueID',
42032: 'CameraOwnerName',
42033: 'BodySerialNumber',
42034: 'LensSpecification',
42035: 'LensMake',
42036: 'LensModel',
42037: 'LensSerialNumber',
42240: 'Gamma',
59932: 'Padding',
59933: 'OffsetSchema',
65000: 'OwnerName',
65001: 'SerialNumber',
65002: 'Lens',
65100: 'RawFile',
65101: 'Converter',
65102: 'WhiteBalance',
65105: 'Exposure',
65106: 'Shadows',
65107: 'Brightness',
65108: 'Contrast',
65109: 'Saturation',
65110: 'Sharpness',
65111: 'Smoothness',
65112: 'MoireFilter',
}
def GPS_TAGS():
return {
0: 'GPSVersionID',
1: 'GPSLatitudeRef',
2: 'GPSLatitude',
3: 'GPSLongitudeRef',
4: 'GPSLongitude',
5: 'GPSAltitudeRef',
6: 'GPSAltitude',
7: 'GPSTimeStamp',
8: 'GPSSatellites',
9: 'GPSStatus',
10: 'GPSMeasureMode',
11: 'GPSDOP',
12: 'GPSSpeedRef',
13: 'GPSSpeed',
14: 'GPSTrackRef',
15: 'GPSTrack',
16: 'GPSImgDirectionRef',
17: 'GPSImgDirection',
18: 'GPSMapDatum',
19: 'GPSDestLatitudeRef',
20: 'GPSDestLatitude',
21: 'GPSDestLongitudeRef',
22: 'GPSDestLongitude',
23: 'GPSDestBearingRef',
24: 'GPSDestBearing',
25: 'GPSDestDistanceRef',
26: 'GPSDestDistance',
27: 'GPSProcessingMethod',
28: 'GPSAreaInformation',
29: 'GPSDateStamp',
30: 'GPSDifferential',
31: 'GPSHPositioningError',
}
def IOP_TAGS():
return {
1: 'InteroperabilityIndex',
2: 'InteroperabilityVersion',
4096: 'RelatedImageFileFormat',
4097: 'RelatedImageWidth',
4098: 'RelatedImageLength',
}
def CZ_LSMINFO():
return [
('MagicNumber', 'u4'),
('StructureSize', 'i4'),
('DimensionX', 'i4'),
('DimensionY', 'i4'),
('DimensionZ', 'i4'),
('DimensionChannels', 'i4'),
('DimensionTime', 'i4'),
('DataType', 'i4'), # DATATYPES
('ThumbnailX', 'i4'),
('ThumbnailY', 'i4'),
('VoxelSizeX', 'f8'),
('VoxelSizeY', 'f8'),
('VoxelSizeZ', 'f8'),
('OriginX', 'f8'),
('OriginY', 'f8'),
('OriginZ', 'f8'),
('ScanType', 'u2'),
('SpectralScan', 'u2'),
('TypeOfData', 'u4'), # TYPEOFDATA
('OffsetVectorOverlay', 'u4'),
('OffsetInputLut', 'u4'),
('OffsetOutputLut', 'u4'),
('OffsetChannelColors', 'u4'),
('TimeIntervall', 'f8'),
('OffsetChannelDataTypes', 'u4'),
('OffsetScanInformation', 'u4'), # SCANINFO
('OffsetKsData', 'u4'),
('OffsetTimeStamps', 'u4'),
('OffsetEventList', 'u4'),
('OffsetRoi', 'u4'),
('OffsetBleachRoi', 'u4'),
('OffsetNextRecording', 'u4'),
# LSM 2.0 ends here
('DisplayAspectX', 'f8'),
('DisplayAspectY', 'f8'),
('DisplayAspectZ', 'f8'),
('DisplayAspectTime', 'f8'),
('OffsetMeanOfRoisOverlay', 'u4'),
('OffsetTopoIsolineOverlay', 'u4'),
('OffsetTopoProfileOverlay', 'u4'),
('OffsetLinescanOverlay', 'u4'),
('ToolbarFlags', 'u4'),
('OffsetChannelWavelength', 'u4'),
('OffsetChannelFactors', 'u4'),
('ObjectiveSphereCorrection', 'f8'),
('OffsetUnmixParameters', 'u4'),
# LSM 3.2, 4.0 end here
('OffsetAcquisitionParameters', 'u4'),
('OffsetCharacteristics', 'u4'),
('OffsetPalette', 'u4'),
('TimeDifferenceX', 'f8'),
('TimeDifferenceY', 'f8'),
('TimeDifferenceZ', 'f8'),
('InternalUse1', 'u4'),
('DimensionP', 'i4'),
('DimensionM', 'i4'),
('DimensionsReserved', '16i4'),
('OffsetTilePositions', 'u4'),
('', '9u4'), # Reserved
('OffsetPositions', 'u4'),
# ('', '21u4'), # must be 0
]
def CZ_LSMINFO_READERS():
# Import functions for CZ_LSMINFO sub-records
# TODO: read more CZ_LSMINFO sub-records
return {
'ScanInformation': read_lsm_scaninfo,
'TimeStamps': read_lsm_timestamps,
'EventList': read_lsm_eventlist,
'ChannelColors': read_lsm_channelcolors,
'Positions': read_lsm_floatpairs,
'TilePositions': read_lsm_floatpairs,
'VectorOverlay': None,
'InputLut': None,
'OutputLut': None,
'TimeIntervall': None,
'ChannelDataTypes': None,
'KsData': None,
'Roi': None,
'BleachRoi': None,
'NextRecording': None,
'MeanOfRoisOverlay': None,
'TopoIsolineOverlay': None,
'TopoProfileOverlay': None,
'ChannelWavelength': None,
'SphereCorrection': None,
'ChannelFactors': None,
'UnmixParameters': None,
'AcquisitionParameters': None,
'Characteristics': None,
}
def CZ_LSMINFO_SCANTYPE():
# Map CZ_LSMINFO.ScanType to dimension order
return {
0: 'XYZCT', # 'Stack' normal x-y-z-scan
1: 'XYZCT', # 'Z-Scan' x-z-plane Y=1
2: 'XYZCT', # 'Line'
3: 'XYTCZ', # 'Time Series Plane' time series x-y XYCTZ ? Z=1
4: 'XYZTC', # 'Time Series z-Scan' time series x-z
5: 'XYTCZ', # 'Time Series Mean-of-ROIs'
6: 'XYZTC', # 'Time Series Stack' time series x-y-z
7: 'XYCTZ', # Spline Scan
8: 'XYCZT', # Spline Plane x-z
9: 'XYTCZ', # Time Series Spline Plane x-z
10: 'XYZCT', # 'Time Series Point' point mode
}
def CZ_LSMINFO_DIMENSIONS():
# Map dimension codes to CZ_LSMINFO attribute
return {
'X': 'DimensionX',
'Y': 'DimensionY',
'Z': 'DimensionZ',
'C': 'DimensionChannels',
'T': 'DimensionTime',
'P': 'DimensionP',
'M': 'DimensionM',
}
def CZ_LSMINFO_DATATYPES():
# Description of CZ_LSMINFO.DataType
return {
0: 'varying data types',
1: '8 bit unsigned integer',
2: '12 bit unsigned integer',
5: '32 bit float',
}
def CZ_LSMINFO_TYPEOFDATA():
# Description of CZ_LSMINFO.TypeOfData
return {
0: 'Original scan data',
1: 'Calculated data',
2: '3D reconstruction',
3: 'Topography height map',
}
def CZ_LSMINFO_SCANINFO_ARRAYS():
return {
0x20000000: 'Tracks',
0x30000000: 'Lasers',
0x60000000: 'DetectionChannels',
0x80000000: 'IlluminationChannels',
0xa0000000: 'BeamSplitters',
0xc0000000: 'DataChannels',
0x11000000: 'Timers',
0x13000000: 'Markers',
}
def CZ_LSMINFO_SCANINFO_STRUCTS():
return {
# 0x10000000: "Recording",
0x40000000: 'Track',
0x50000000: 'Laser',
0x70000000: 'DetectionChannel',
0x90000000: 'IlluminationChannel',
0xb0000000: 'BeamSplitter',
0xd0000000: 'DataChannel',
0x12000000: 'Timer',
0x14000000: 'Marker',
}
def CZ_LSMINFO_SCANINFO_ATTRIBUTES():
return {
# Recording
0x10000001: 'Name',
0x10000002: 'Description',
0x10000003: 'Notes',
0x10000004: 'Objective',
0x10000005: 'ProcessingSummary',
0x10000006: 'SpecialScanMode',
0x10000007: 'ScanType',
0x10000008: 'ScanMode',
0x10000009: 'NumberOfStacks',
0x1000000a: 'LinesPerPlane',
0x1000000b: 'SamplesPerLine',
0x1000000c: 'PlanesPerVolume',
0x1000000d: 'ImagesWidth',
0x1000000e: 'ImagesHeight',
0x1000000f: 'ImagesNumberPlanes',
0x10000010: 'ImagesNumberStacks',
0x10000011: 'ImagesNumberChannels',
0x10000012: 'LinscanXySize',
0x10000013: 'ScanDirection',
0x10000014: 'TimeSeries',
0x10000015: 'OriginalScanData',
0x10000016: 'ZoomX',
0x10000017: 'ZoomY',
0x10000018: 'ZoomZ',
0x10000019: 'Sample0X',
0x1000001a: 'Sample0Y',
0x1000001b: 'Sample0Z',
0x1000001c: 'SampleSpacing',
0x1000001d: 'LineSpacing',
0x1000001e: 'PlaneSpacing',
0x1000001f: 'PlaneWidth',
0x10000020: 'PlaneHeight',
0x10000021: 'VolumeDepth',
0x10000023: 'Nutation',
0x10000034: 'Rotation',
0x10000035: 'Precession',
0x10000036: 'Sample0time',
0x10000037: 'StartScanTriggerIn',
0x10000038: 'StartScanTriggerOut',
0x10000039: 'StartScanEvent',
0x10000040: 'StartScanTime',
0x10000041: 'StopScanTriggerIn',
0x10000042: 'StopScanTriggerOut',
0x10000043: 'StopScanEvent',
0x10000044: 'StopScanTime',
0x10000045: 'UseRois',
0x10000046: 'UseReducedMemoryRois',
0x10000047: 'User',
0x10000048: 'UseBcCorrection',
0x10000049: 'PositionBcCorrection1',
0x10000050: 'PositionBcCorrection2',
0x10000051: 'InterpolationY',
0x10000052: 'CameraBinning',
0x10000053: 'CameraSupersampling',
0x10000054: 'CameraFrameWidth',
0x10000055: 'CameraFrameHeight',
0x10000056: 'CameraOffsetX',
0x10000057: 'CameraOffsetY',
0x10000059: 'RtBinning',
0x1000005a: 'RtFrameWidth',
0x1000005b: 'RtFrameHeight',
0x1000005c: 'RtRegionWidth',
0x1000005d: 'RtRegionHeight',
0x1000005e: 'RtOffsetX',
0x1000005f: 'RtOffsetY',
0x10000060: 'RtZoom',
0x10000061: 'RtLinePeriod',
0x10000062: 'Prescan',
0x10000063: 'ScanDirectionZ',
# Track
0x40000001: 'MultiplexType', # 0 After Line; 1 After Frame
0x40000002: 'MultiplexOrder',
0x40000003: 'SamplingMode', # 0 Sample; 1 Line Avg; 2 Frame Avg
0x40000004: 'SamplingMethod', # 1 Mean; 2 Sum
0x40000005: 'SamplingNumber',
0x40000006: 'Acquire',
0x40000007: 'SampleObservationTime',
0x4000000b: 'TimeBetweenStacks',
0x4000000c: 'Name',
0x4000000d: 'Collimator1Name',
0x4000000e: 'Collimator1Position',
0x4000000f: 'Collimator2Name',
0x40000010: 'Collimator2Position',
0x40000011: 'IsBleachTrack',
0x40000012: 'IsBleachAfterScanNumber',
0x40000013: 'BleachScanNumber',
0x40000014: 'TriggerIn',
0x40000015: 'TriggerOut',
0x40000016: 'IsRatioTrack',
0x40000017: 'BleachCount',
0x40000018: 'SpiCenterWavelength',
0x40000019: 'PixelTime',
0x40000021: 'CondensorFrontlens',
0x40000023: 'FieldStopValue',
0x40000024: 'IdCondensorAperture',
0x40000025: 'CondensorAperture',
0x40000026: 'IdCondensorRevolver',
0x40000027: 'CondensorFilter',
0x40000028: 'IdTransmissionFilter1',
0x40000029: 'IdTransmission1',
0x40000030: 'IdTransmissionFilter2',
0x40000031: 'IdTransmission2',
0x40000032: 'RepeatBleach',
0x40000033: 'EnableSpotBleachPos',
0x40000034: 'SpotBleachPosx',
0x40000035: 'SpotBleachPosy',
0x40000036: 'SpotBleachPosz',
0x40000037: 'IdTubelens',
0x40000038: 'IdTubelensPosition',
0x40000039: 'TransmittedLight',
0x4000003a: 'ReflectedLight',
0x4000003b: 'SimultanGrabAndBleach',
0x4000003c: 'BleachPixelTime',
# Laser
0x50000001: 'Name',
0x50000002: 'Acquire',
0x50000003: 'Power',
# DetectionChannel
0x70000001: 'IntegrationMode',
0x70000002: 'SpecialMode',
0x70000003: 'DetectorGainFirst',
0x70000004: 'DetectorGainLast',
0x70000005: 'AmplifierGainFirst',
0x70000006: 'AmplifierGainLast',
0x70000007: 'AmplifierOffsFirst',
0x70000008: 'AmplifierOffsLast',
0x70000009: 'PinholeDiameter',
0x7000000a: 'CountingTrigger',
0x7000000b: 'Acquire',
0x7000000c: 'PointDetectorName',
0x7000000d: 'AmplifierName',
0x7000000e: 'PinholeName',
0x7000000f: 'FilterSetName',
0x70000010: 'FilterName',
0x70000013: 'IntegratorName',
0x70000014: 'ChannelName',
0x70000015: 'DetectorGainBc1',
0x70000016: 'DetectorGainBc2',
0x70000017: 'AmplifierGainBc1',
0x70000018: 'AmplifierGainBc2',
0x70000019: 'AmplifierOffsetBc1',
0x70000020: 'AmplifierOffsetBc2',
0x70000021: 'SpectralScanChannels',
0x70000022: 'SpiWavelengthStart',
0x70000023: 'SpiWavelengthStop',
0x70000026: 'DyeName',
0x70000027: 'DyeFolder',
# IlluminationChannel
0x90000001: 'Name',
0x90000002: 'Power',
0x90000003: 'Wavelength',
0x90000004: 'Aquire',
0x90000005: 'DetchannelName',
0x90000006: 'PowerBc1',
0x90000007: 'PowerBc2',
# BeamSplitter
0xb0000001: 'FilterSet',
0xb0000002: 'Filter',
0xb0000003: 'Name',
# DataChannel
0xd0000001: 'Name',
0xd0000003: 'Acquire',
0xd0000004: 'Color',
0xd0000005: 'SampleType',
0xd0000006: 'BitsPerSample',
0xd0000007: 'RatioType',
0xd0000008: 'RatioTrack1',
0xd0000009: 'RatioTrack2',
0xd000000a: 'RatioChannel1',
0xd000000b: 'RatioChannel2',
0xd000000c: 'RatioConst1',
0xd000000d: 'RatioConst2',
0xd000000e: 'RatioConst3',
0xd000000f: 'RatioConst4',
0xd0000010: 'RatioConst5',
0xd0000011: 'RatioConst6',
0xd0000012: 'RatioFirstImages1',
0xd0000013: 'RatioFirstImages2',
0xd0000014: 'DyeName',
0xd0000015: 'DyeFolder',
0xd0000016: 'Spectrum',
0xd0000017: 'Acquire',
# Timer
0x12000001: 'Name',
0x12000002: 'Description',
0x12000003: 'Interval',
0x12000004: 'TriggerIn',
0x12000005: 'TriggerOut',
0x12000006: 'ActivationTime',
0x12000007: 'ActivationNumber',
# Marker
0x14000001: 'Name',
0x14000002: 'Description',
0x14000003: 'TriggerIn',
0x14000004: 'TriggerOut',
}
def NIH_IMAGE_HEADER():
return [
('FileID', 'a8'),
('nLines', 'i2'),
('PixelsPerLine', 'i2'),
('Version', 'i2'),
('OldLutMode', 'i2'),
('OldnColors', 'i2'),
('Colors', 'u1', (3, 32)),
('OldColorStart', 'i2'),
('ColorWidth', 'i2'),
('ExtraColors', 'u2', (6, 3)),
('nExtraColors', 'i2'),
('ForegroundIndex', 'i2'),
('BackgroundIndex', 'i2'),
('XScale', 'f8'),
('Unused2', 'i2'),
('Unused3', 'i2'),
('UnitsID', 'i2'), # NIH_UNITS_TYPE
('p1', [('x', 'i2'), ('y', 'i2')]),
('p2', [('x', 'i2'), ('y', 'i2')]),
('CurveFitType', 'i2'), # NIH_CURVEFIT_TYPE
('nCoefficients', 'i2'),
('Coeff', 'f8', 6),
('UMsize', 'u1'),
('UM', 'a15'),
('UnusedBoolean', 'u1'),
('BinaryPic', 'b1'),
('SliceStart', 'i2'),
('SliceEnd', 'i2'),
('ScaleMagnification', 'f4'),
('nSlices', 'i2'),
('SliceSpacing', 'f4'),
('CurrentSlice', 'i2'),
('FrameInterval', 'f4'),
('PixelAspectRatio', 'f4'),
('ColorStart', 'i2'),
('ColorEnd', 'i2'),
('nColors', 'i2'),
('Fill1', '3u2'),
('Fill2', '3u2'),
('Table', 'u1'), # NIH_COLORTABLE_TYPE
('LutMode', 'u1'), # NIH_LUTMODE_TYPE
('InvertedTable', 'b1'),
('ZeroClip', 'b1'),
('XUnitSize', 'u1'),
('XUnit', 'a11'),
('StackType', 'i2'), # NIH_STACKTYPE_TYPE
# ('UnusedBytes', 'u1', 200)
]
def NIH_COLORTABLE_TYPE():
return ('CustomTable', 'AppleDefault', 'Pseudo20', 'Pseudo32',
'Rainbow', 'Fire1', 'Fire2', 'Ice', 'Grays', 'Spectrum')
def NIH_LUTMODE_TYPE():
return ('PseudoColor', 'OldAppleDefault', 'OldSpectrum', 'GrayScale',
'ColorLut', 'CustomGrayscale')
def NIH_CURVEFIT_TYPE():
return ('StraightLine', 'Poly2', 'Poly3', 'Poly4', 'Poly5', 'ExpoFit',
'PowerFit', 'LogFit', 'RodbardFit', 'SpareFit1',
'Uncalibrated', 'UncalibratedOD')
def NIH_UNITS_TYPE():
return ('Nanometers', 'Micrometers', 'Millimeters', 'Centimeters',
'Meters', 'Kilometers', 'Inches', 'Feet', 'Miles', 'Pixels',
'OtherUnits')
def NIH_STACKTYPE_TYPE():
return ('VolumeStack', 'RGBStack', 'MovieStack', 'HSVStack')
def TVIPS_HEADER_V1():
# TVIPS TemData structure from EMMENU Help file
return [
('Version', 'i4'),
('CommentV1', 'a80'),
('HighTension', 'i4'),
('SphericalAberration', 'i4'),
('IlluminationAperture', 'i4'),
('Magnification', 'i4'),
('PostMagnification', 'i4'),
('FocalLength', 'i4'),
('Defocus', 'i4'),
('Astigmatism', 'i4'),
('AstigmatismDirection', 'i4'),
('BiprismVoltage', 'i4'),
('SpecimenTiltAngle', 'i4'),
('SpecimenTiltDirection', 'i4'),
('IlluminationTiltDirection', 'i4'),
('IlluminationTiltAngle', 'i4'),
('ImageMode', 'i4'),
('EnergySpread', 'i4'),
('ChromaticAberration', 'i4'),
('ShutterType', 'i4'),
('DefocusSpread', 'i4'),
('CcdNumber', 'i4'),
('CcdSize', 'i4'),
('OffsetXV1', 'i4'),
('OffsetYV1', 'i4'),
('PhysicalPixelSize', 'i4'),
('Binning', 'i4'),
('ReadoutSpeed', 'i4'),
('GainV1', 'i4'),
('SensitivityV1', 'i4'),
('ExposureTimeV1', 'i4'),
('FlatCorrected', 'i4'),
('DeadPxCorrected', 'i4'),
('ImageMean', 'i4'),
('ImageStd', 'i4'),
('DisplacementX', 'i4'),
('DisplacementY', 'i4'),
('DateV1', 'i4'),
('TimeV1', 'i4'),
('ImageMin', 'i4'),
('ImageMax', 'i4'),
('ImageStatisticsQuality', 'i4'),
]
def TVIPS_HEADER_V2():
return [
('ImageName', 'V160'), # utf16
('ImageFolder', 'V160'),
('ImageSizeX', 'i4'),
('ImageSizeY', 'i4'),
('ImageSizeZ', 'i4'),
('ImageSizeE', 'i4'),
('ImageDataType', 'i4'),
('Date', 'i4'),
('Time', 'i4'),
('Comment', 'V1024'),
('ImageHistory', 'V1024'),
('Scaling', '16f4'),
('ImageStatistics', '16c16'),
('ImageType', 'i4'),
('ImageDisplaType', 'i4'),
('PixelSizeX', 'f4'), # distance between two px in x, [nm]
('PixelSizeY', 'f4'), # distance between two px in y, [nm]
('ImageDistanceZ', 'f4'),
('ImageDistanceE', 'f4'),
('ImageMisc', '32f4'),
('TemType', 'V160'),
('TemHighTension', 'f4'),
('TemAberrations', '32f4'),
('TemEnergy', '32f4'),
('TemMode', 'i4'),
('TemMagnification', 'f4'),
('TemMagnificationCorrection', 'f4'),
('PostMagnification', 'f4'),
('TemStageType', 'i4'),
('TemStagePosition', '5f4'), # x, y, z, a, b
('TemImageShift', '2f4'),
('TemBeamShift', '2f4'),
('TemBeamTilt', '2f4'),
('TilingParameters', '7f4'), # 0: tiling? 1:x 2:y 3: max x
# 4: max y 5: overlap x 6: overlap y
('TemIllumination', '3f4'), # 0: spotsize 1: intensity
('TemShutter', 'i4'),
('TemMisc', '32f4'),
('CameraType', 'V160'),
('PhysicalPixelSizeX', 'f4'),
('PhysicalPixelSizeY', 'f4'),
('OffsetX', 'i4'),
('OffsetY', 'i4'),
('BinningX', 'i4'),
('BinningY', 'i4'),
('ExposureTime', 'f4'),
('Gain', 'f4'),
('ReadoutRate', 'f4'),
('FlatfieldDescription', 'V160'),
('Sensitivity', 'f4'),
('Dose', 'f4'),
('CamMisc', '32f4'),
('FeiMicroscopeInformation', 'V1024'),
('FeiSpecimenInformation', 'V1024'),
('Magic', 'u4'),
]
def MM_HEADER():
# Olympus FluoView MM_Header
MM_DIMENSION = [
('Name', 'a16'),
('Size', 'i4'),
('Origin', 'f8'),
('Resolution', 'f8'),
('Unit', 'a64')]
return [
('HeaderFlag', 'i2'),
('ImageType', 'u1'),
('ImageName', 'a257'),
('OffsetData', 'u4'),
('PaletteSize', 'i4'),
('OffsetPalette0', 'u4'),
('OffsetPalette1', 'u4'),
('CommentSize', 'i4'),
('OffsetComment', 'u4'),
('Dimensions', MM_DIMENSION, 10),
('OffsetPosition', 'u4'),
('MapType', 'i2'),
('MapMin', 'f8'),
('MapMax', 'f8'),
('MinValue', 'f8'),
('MaxValue', 'f8'),
('OffsetMap', 'u4'),
('Gamma', 'f8'),
('Offset', 'f8'),
('GrayChannel', MM_DIMENSION),
('OffsetThumbnail', 'u4'),
('VoiceField', 'i4'),
('OffsetVoiceField', 'u4'),
]
def MM_DIMENSIONS():
# Map FluoView MM_Header.Dimensions to axes characters
return {
'X': 'X',
'Y': 'Y',
'Z': 'Z',
'T': 'T',
'CH': 'C',
'WAVELENGTH': 'C',
'TIME': 'T',
'XY': 'R',
'EVENT': 'V',
'EXPOSURE': 'L',
}
def UIC_TAGS():
# Map Universal Imaging Corporation MetaMorph internal tag ids to
# name and type
from fractions import Fraction
return [
('AutoScale', int),
('MinScale', int),
('MaxScale', int),
('SpatialCalibration', int),
('XCalibration', Fraction),
('YCalibration', Fraction),
('CalibrationUnits', str),
('Name', str),
('ThreshState', int),
('ThreshStateRed', int),
('tagid_10', None), # undefined
('ThreshStateGreen', int),
('ThreshStateBlue', int),
('ThreshStateLo', int),
('ThreshStateHi', int),
('Zoom', int),
('CreateTime', julian_datetime),
('LastSavedTime', julian_datetime),
('currentBuffer', int),
('grayFit', None),
('grayPointCount', None),
('grayX', Fraction),
('grayY', Fraction),
('grayMin', Fraction),
('grayMax', Fraction),
('grayUnitName', str),
('StandardLUT', int),
('wavelength', int),
('StagePosition', '(%i,2,2)u4'), # N xy positions as fract
('CameraChipOffset', '(%i,2,2)u4'), # N xy offsets as fract
('OverlayMask', None),
('OverlayCompress', None),
('Overlay', None),
('SpecialOverlayMask', None),
('SpecialOverlayCompress', None),
('SpecialOverlay', None),
('ImageProperty', read_uic_image_property),
('StageLabel', '%ip'), # N str
('AutoScaleLoInfo', Fraction),
('AutoScaleHiInfo', Fraction),
('AbsoluteZ', '(%i,2)u4'), # N fractions
('AbsoluteZValid', '(%i,)u4'), # N long
('Gamma', 'I'), # 'I' uses offset
('GammaRed', 'I'),
('GammaGreen', 'I'),
('GammaBlue', 'I'),
('CameraBin', '2I'),
('NewLUT', int),
('ImagePropertyEx', None),
('PlaneProperty', int),
('UserLutTable', '(256,3)u1'),
('RedAutoScaleInfo', int),
('RedAutoScaleLoInfo', Fraction),
('RedAutoScaleHiInfo', Fraction),
('RedMinScaleInfo', int),
('RedMaxScaleInfo', int),
('GreenAutoScaleInfo', int),
('GreenAutoScaleLoInfo', Fraction),
('GreenAutoScaleHiInfo', Fraction),
('GreenMinScaleInfo', int),
('GreenMaxScaleInfo', int),
('BlueAutoScaleInfo', int),
('BlueAutoScaleLoInfo', Fraction),
('BlueAutoScaleHiInfo', Fraction),
('BlueMinScaleInfo', int),
('BlueMaxScaleInfo', int),
# ('OverlayPlaneColor', read_uic_overlay_plane_color),
]
def PILATUS_HEADER():
# PILATUS CBF Header Specification, Version 1.4
# Map key to [value_indices], type
return {
'Detector': ([slice(1, None)], str),
'Pixel_size': ([1, 4], float),
'Silicon': ([3], float),
'Exposure_time': ([1], float),
'Exposure_period': ([1], float),
'Tau': ([1], float),
'Count_cutoff': ([1], int),
'Threshold_setting': ([1], float),
'Gain_setting': ([1, 2], str),
'N_excluded_pixels': ([1], int),
'Excluded_pixels': ([1], str),
'Flat_field': ([1], str),
'Trim_file': ([1], str),
'Image_path': ([1], str),
# optional
'Wavelength': ([1], float),
'Energy_range': ([1, 2], float),
'Detector_distance': ([1], float),
'Detector_Voffset': ([1], float),
'Beam_xy': ([1, 2], float),
'Flux': ([1], str),
'Filter_transmission': ([1], float),
'Start_angle': ([1], float),
'Angle_increment': ([1], float),
'Detector_2theta': ([1], float),
'Polarization': ([1], float),
'Alpha': ([1], float),
'Kappa': ([1], float),
'Phi': ([1], float),
'Phi_increment': ([1], float),
'Chi': ([1], float),
'Chi_increment': ([1], float),
'Oscillation_axis': ([slice(1, None)], str),
'N_oscillations': ([1], int),
'Start_position': ([1], float),
'Position_increment': ([1], float),
'Shutter_time': ([1], float),
'Omega': ([1], float),
'Omega_increment': ([1], float)
}
def REVERSE_BITORDER_BYTES():
# Bytes with reversed bitorder
return (
b'\x00\x80@\xc0 \xa0`\xe0\x10\x90P\xd00\xb0p\xf0\x08\x88H\xc8('
b'\xa8h\xe8\x18\x98X\xd88\xb8x\xf8\x04\x84D\xc4$\xa4d\xe4\x14'
b'\x94T\xd44\xb4t\xf4\x0c\x8cL\xcc,\xacl\xec\x1c\x9c\\\xdc<\xbc|'
b'\xfc\x02\x82B\xc2"\xa2b\xe2\x12\x92R\xd22\xb2r\xf2\n\x8aJ\xca*'
b'\xaaj\xea\x1a\x9aZ\xda:\xbaz\xfa\x06\x86F\xc6&\xa6f\xe6\x16'
b'\x96V\xd66\xb6v\xf6\x0e\x8eN\xce.\xaen\xee\x1e\x9e^\xde>\xbe~'
b'\xfe\x01\x81A\xc1!\xa1a\xe1\x11\x91Q\xd11\xb1q\xf1\t\x89I\xc9)'
b'\xa9i\xe9\x19\x99Y\xd99\xb9y\xf9\x05\x85E\xc5%\xa5e\xe5\x15'
b'\x95U\xd55\xb5u\xf5\r\x8dM\xcd-\xadm\xed\x1d\x9d]\xdd=\xbd}'
b'\xfd\x03\x83C\xc3#\xa3c\xe3\x13\x93S\xd33\xb3s\xf3\x0b\x8bK'
b'\xcb+\xabk\xeb\x1b\x9b[\xdb;\xbb{\xfb\x07\x87G\xc7\'\xa7g\xe7'
b'\x17\x97W\xd77\xb7w\xf7\x0f\x8fO\xcf/\xafo\xef\x1f\x9f_'
b'\xdf?\xbf\x7f\xff')
def REVERSE_BITORDER_ARRAY():
# Numpy array of bytes with reversed bitorder
return numpy.fromstring(TIFF.REVERSE_BITORDER_BYTES, dtype='uint8')
def ALLOCATIONGRANULARITY():
# alignment for writing contiguous data to TIFF
import mmap # delayed import
return mmap.ALLOCATIONGRANULARITY
# Max line length of printed output
PRINT_LINE_WIDTH = 100
# Max number of lines to print
PRINT_MAX_LINES = 512
def read_tags(fh, byteorder, offsetsize, tagnames,
customtags=None, maxifds=None):
"""Read tags from chain of IFDs and return as list of dicts.
The file handle position must be at a valid IFD header.
"""
if offsetsize == 4:
offsetformat = byteorder+'I'
tagnosize = 2
tagnoformat = byteorder+'H'
tagsize = 12
tagformat1 = byteorder+'HH'
tagformat2 = byteorder+'I4s'
elif offsetsize == 8:
offsetformat = byteorder+'Q'
tagnosize = 8
tagnoformat = byteorder+'Q'
tagsize = 20
tagformat1 = byteorder+'HH'
tagformat2 = byteorder+'Q8s'
else:
raise ValueError("invalid offset size")
if customtags is None:
customtags = {}
if maxifds is None:
maxifds = 2**32
result = []
unpack = struct.unpack
offset = fh.tell()
while len(result) < maxifds:
# loop over IFDs
try:
tagno = unpack(tagnoformat, fh.read(tagnosize))[0]
if tagno > 4096:
raise ValueError("suspicious number of tags")
except Exception:
warnings.warn("corrupted tag list at offset %i" % offset)
break
tags = {}
data = fh.read(tagsize * tagno)
pos = fh.tell()
index = 0
for _ in range(tagno):
code, type_ = unpack(tagformat1, data[index:index+4])
count, value = unpack(tagformat2, data[index+4:index+tagsize])
index += tagsize
name = tagnames.get(code, str(code))
try:
dtype = TIFF.DATA_FORMATS[type_]
except KeyError:
raise TiffTag.Error("unknown tag data type %i" % type_)
fmt = '%s%i%s' % (byteorder, count * int(dtype[0]), dtype[1])
size = struct.calcsize(fmt)
if size > offsetsize or code in customtags:
offset = unpack(offsetformat, value)[0]
if offset < 8 or offset > fh.size - size:
raise TiffTag.Error("invalid tag value offset")
fh.seek(offset)
if code in customtags:
readfunc = customtags[code][1]
value = readfunc(fh, byteorder, dtype, count, offsetsize)
elif code in tagnames or dtype[-1] == 's':
value = unpack(fmt, fh.read(size))
else:
value = read_numpy(fh, byteorder, dtype, count, offsetsize)
else:
value = unpack(fmt, value[:size])
if code not in customtags and code not in TIFF.TAG_TUPLE:
if len(value) == 1:
value = value[0]
if type_ != 7 and dtype[-1] == 's' and isinstance(value, bytes):
# TIFF ASCII fields can contain multiple strings,
# each terminated with a NUL
value = bytes2str(stripascii(value))
tags[name] = value
result.append(tags)
# read offset to next page
fh.seek(pos)
offset = unpack(offsetformat, fh.read(offsetsize))[0]
if offset == 0:
break
if offset >= fh.size:
warnings.warn("invalid page offset (%i)" % offset)
break
fh.seek(offset)
if maxifds == 1:
result = result[0]
return result
def read_exif_ifd(fh, byteorder, dtype, count, offsetsize):
"""Read EXIF tags from file and return as dict."""
tags = read_tags(fh, byteorder, offsetsize, TIFF.EXIF_TAGS, maxifds=1)
if 'ExifVersion' in tags:
tags['ExifVersion'] = bytes2str(tags['ExifVersion'])
return tags
def read_gps_ifd(fh, byteorder, dtype, count, offsetsize):
"""Read GPS tags from file and return as dict."""
return read_tags(fh, byteorder, offsetsize, TIFF.GPS_TAGS, maxifds=1)
def read_interoperability_ifd(fh, byteorder, dtype, count, offsetsize):
"""Read Interoperability tags from file and return as dict."""
tag_names = {1: 'InteroperabilityIndex'}
return read_tags(fh, byteorder, offsetsize, tag_names, maxifds=1)
def read_bytes(fh, byteorder, dtype, count, offsetsize):
"""Read tag data from file and return as byte string."""
dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]
return fh.read_array(dtype, count).tostring()
def read_utf8(fh, byteorder, dtype, count, offsetsize):
"""Read tag data from file and return as unicode string."""
return fh.read(count).decode('utf-8')
def read_numpy(fh, byteorder, dtype, count, offsetsize):
"""Read tag data from file and return as numpy array."""
dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]
return fh.read_array(dtype, count)
def read_colormap(fh, byteorder, dtype, count, offsetsize):
"""Read ColorMap data from file and return as numpy array."""
cmap = fh.read_array(byteorder+dtype[-1], count)
cmap.shape = (3, -1)
return cmap
def read_json(fh, byteorder, dtype, count, offsetsize):
"""Read JSON tag data from file and return as object."""
data = fh.read(count)
try:
return json.loads(unicode(stripnull(data), 'utf-8'))
except ValueError:
warnings.warn("invalid JSON '%s'" % data)
def read_mm_header(fh, byteorder, dtype, count, offsetsize):
"""Read FluoView mm_header tag from file and return as dict."""
mmh = fh.read_record(TIFF.MM_HEADER, byteorder=byteorder)
mmh = recarray2dict(mmh)
mmh['Dimensions'] = [
(bytes2str(d[0]).strip(), d[1], d[2], d[3], bytes2str(d[4]).strip())
for d in mmh['Dimensions']]
d = mmh['GrayChannel']
mmh['GrayChannel'] = (
bytes2str(d[0]).strip(), d[1], d[2], d[3], bytes2str(d[4]).strip())
return mmh
def read_mm_stamp(fh, byteorder, dtype, count, offsetsize):
"""Read FluoView mm_stamp tag from file and return as numpy.ndarray."""
return fh.read_array(byteorder+'f8', 8)
def read_uic1tag(fh, byteorder, dtype, count, offsetsize, planecount=None):
"""Read MetaMorph STK UIC1Tag from file and return as dict.
Return empty dictionary if planecount is unknown.
"""
assert dtype in ('2I', '1I') and byteorder == '<'
result = {}
if dtype == '2I':
# pre MetaMorph 2.5 (not tested)
values = fh.read_array('<u4', 2*count).reshape(count, 2)
result = {'ZDistance': values[:, 0] / values[:, 1]}
elif planecount:
for _ in range(count):
tagid = struct.unpack('<I', fh.read(4))[0]
if tagid in (28, 29, 37, 40, 41):
# silently skip unexpected tags
fh.read(4)
continue
name, value = read_uic_tag(fh, tagid, planecount, offset=True)
result[name] = value
return result
def read_uic2tag(fh, byteorder, dtype, planecount, offsetsize):
"""Read MetaMorph STK UIC2Tag from file and return as dict."""
assert dtype == '2I' and byteorder == '<'
values = fh.read_array('<u4', 6*planecount).reshape(planecount, 6)
return {
'ZDistance': values[:, 0] / values[:, 1],
'DateCreated': values[:, 2], # julian days
'TimeCreated': values[:, 3], # milliseconds
'DateModified': values[:, 4], # julian days
'TimeModified': values[:, 5]} # milliseconds
def read_uic3tag(fh, byteorder, dtype, planecount, offsetsize):
"""Read MetaMorph STK UIC3Tag from file and return as dict."""
assert dtype == '2I' and byteorder == '<'
values = fh.read_array('<u4', 2*planecount).reshape(planecount, 2)
return {'Wavelengths': values[:, 0] / values[:, 1]}
def read_uic4tag(fh, byteorder, dtype, planecount, offsetsize):
"""Read MetaMorph STK UIC4Tag from file and return as dict."""
assert dtype == '1I' and byteorder == '<'
result = {}
while True:
tagid = struct.unpack('<H', fh.read(2))[0]
if tagid == 0:
break
name, value = read_uic_tag(fh, tagid, planecount, offset=False)
result[name] = value
return result
def read_uic_tag(fh, tagid, planecount, offset):
"""Read a single UIC tag value from file and return tag name and value.
UIC1Tags use an offset.
"""
def read_int(count=1):
value = struct.unpack('<%iI' % count, fh.read(4*count))
return value[0] if count == 1 else value
try:
name, dtype = TIFF.UIC_TAGS[tagid]
except IndexError:
# unknown tag
return '_TagId%i' % tagid, read_int()
Fraction = TIFF.UIC_TAGS[4][1]
if offset:
pos = fh.tell()
if dtype not in (int, None):
off = read_int()
if off < 8:
if dtype is str:
return name, ''
warnings.warn("invalid offset for uic tag '%s': %i" %
(name, off))
return name, off
fh.seek(off)
if dtype is None:
# skip
name = '_' + name
value = read_int()
elif dtype is int:
# int
value = read_int()
elif dtype is Fraction:
# fraction
value = read_int(2)
value = value[0] / value[1]
elif dtype is julian_datetime:
# datetime
value = julian_datetime(*read_int(2))
elif dtype is read_uic_image_property:
# ImagePropertyEx
value = read_uic_image_property(fh)
elif dtype is str:
# pascal string
size = read_int()
if 0 <= size < 2**10:
value = struct.unpack('%is' % size, fh.read(size))[0][:-1]
value = bytes2str(stripnull(value))
elif offset:
value = ''
warnings.warn("corrupt string in uic tag '%s'" % name)
else:
raise ValueError("invalid string size %i" % size)
elif dtype == '%ip':
# sequence of pascal strings
value = []
for _ in range(planecount):
size = read_int()
if 0 <= size < 2**10:
string = struct.unpack('%is' % size, fh.read(size))[0][:-1]
string = bytes2str(stripnull(string))
value.append(string)
elif offset:
warnings.warn("corrupt string in uic tag '%s'" % name)
else:
raise ValueError("invalid string size %i" % size)
else:
# struct or numpy type
dtype = '<' + dtype
if '%i' in dtype:
dtype = dtype % planecount
if '(' in dtype:
# numpy type
value = fh.read_array(dtype, 1)[0]
if value.shape[-1] == 2:
# assume fractions
value = value[..., 0] / value[..., 1]
else:
# struct format
value = struct.unpack(dtype, fh.read(struct.calcsize(dtype)))
if len(value) == 1:
value = value[0]
if offset:
fh.seek(pos + 4)
return name, value
def read_uic_image_property(fh):
"""Read UIC ImagePropertyEx tag from file and return as dict."""
# TODO: test this
size = struct.unpack('B', fh.read(1))[0]
name = struct.unpack('%is' % size, fh.read(size))[0][:-1]
flags, prop = struct.unpack('<IB', fh.read(5))
if prop == 1:
value = struct.unpack('II', fh.read(8))
value = value[0] / value[1]
else:
size = struct.unpack('B', fh.read(1))[0]
value = struct.unpack('%is' % size, fh.read(size))[0]
return dict(name=name, flags=flags, value=value)
def read_cz_lsminfo(fh, byteorder, dtype, count, offsetsize):
"""Read CZ_LSMINFO tag from file and return as dict."""
assert byteorder == '<'
magic_number, structure_size = struct.unpack('<II', fh.read(8))
if magic_number not in (50350412, 67127628):
raise ValueError("invalid CZ_LSMINFO structure")
fh.seek(-8, 1)
if structure_size < numpy.dtype(TIFF.CZ_LSMINFO).itemsize:
# adjust structure according to structure_size
lsminfo = []
size = 0
for name, dtype in TIFF.CZ_LSMINFO:
size += numpy.dtype(dtype).itemsize
if size > structure_size:
break
lsminfo.append((name, dtype))
else:
lsminfo = TIFF.CZ_LSMINFO
lsminfo = fh.read_record(lsminfo, byteorder=byteorder)
lsminfo = recarray2dict(lsminfo)
# read LSM info subrecords at offsets
for name, reader in TIFF.CZ_LSMINFO_READERS.items():
if reader is None:
continue
offset = lsminfo.get('Offset' + name, 0)
if offset < 8:
continue
fh.seek(offset)
try:
lsminfo[name] = reader(fh)
except ValueError:
pass
return lsminfo
def read_lsm_floatpairs(fh):
"""Read LSM sequence of float pairs from file and return as list."""
size = struct.unpack('<i', fh.read(4))[0]
return fh.read_array('<2f8', count=size)
def read_lsm_positions(fh):
"""Read LSM positions from file and return as list."""
size = struct.unpack('<I', fh.read(4))[0]
return fh.read_array('<2f8', count=size)
def read_lsm_timestamps(fh):
"""Read LSM time stamps from file and return as list."""
size, count = struct.unpack('<ii', fh.read(8))
if size != (8 + 8 * count):
warnings.warn("invalid LSM TimeStamps block")
return []
# return struct.unpack('<%dd' % count, fh.read(8*count))
return fh.read_array('<f8', count=count)
def read_lsm_eventlist(fh):
"""Read LSM events from file and return as list of (time, type, text)."""
count = struct.unpack('<II', fh.read(8))[1]
events = []
while count > 0:
esize, etime, etype = struct.unpack('<IdI', fh.read(16))
etext = bytes2str(stripnull(fh.read(esize - 16)))
events.append((etime, etype, etext))
count -= 1
return events
def read_lsm_channelcolors(fh):
"""Read LSM ChannelColors structure from file and return as dict."""
result = {'Mono': False, 'Colors': [], 'ColorNames': []}
pos = fh.tell()
(size, ncolors, nnames,
coffset, noffset, mono) = struct.unpack('<IIIIII', fh.read(24))
if ncolors != nnames:
warnings.warn("invalid LSM ChannelColors structure")
return result
result['Mono'] = bool(mono)
# Colors
fh.seek(pos + coffset)
colors = fh.read_array('uint8', count=ncolors*4).reshape((ncolors, 4))
result['Colors'] = colors.tolist()
# ColorNames
fh.seek(pos + noffset)
buffer = fh.read(size - noffset)
names = []
while len(buffer) > 4:
size = struct.unpack('<I', buffer[:4])[0]
names.append(bytes2str(buffer[4:3+size]))
buffer = buffer[4+size:]
result['ColorNames'] = names
return result
def read_lsm_scaninfo(fh):
"""Read LSM ScanInfo structure from file and return as dict."""
block = {}
blocks = [block]
unpack = struct.unpack
if struct.unpack('<I', fh.read(4))[0] != 0x10000000:
# not a Recording sub block
warnings.warn("invalid LSM ScanInfo structure")
return block
fh.read(8)
while True:
entry, dtype, size = unpack('<III', fh.read(12))
if dtype == 2:
# ascii
value = bytes2str(stripnull(fh.read(size)))
elif dtype == 4:
# long
value = unpack('<i', fh.read(4))[0]
elif dtype == 5:
# rational
value = unpack('<d', fh.read(8))[0]
else:
value = 0
if entry in TIFF.CZ_LSMINFO_SCANINFO_ARRAYS:
blocks.append(block)
name = TIFF.CZ_LSMINFO_SCANINFO_ARRAYS[entry]
newobj = []
block[name] = newobj
block = newobj
elif entry in TIFF.CZ_LSMINFO_SCANINFO_STRUCTS:
blocks.append(block)
newobj = {}
block.append(newobj)
block = newobj
elif entry in TIFF.CZ_LSMINFO_SCANINFO_ATTRIBUTES:
name = TIFF.CZ_LSMINFO_SCANINFO_ATTRIBUTES[entry]
block[name] = value
elif entry == 0xffffffff:
# end sub block
block = blocks.pop()
else:
# unknown entry
block["Entry0x%x" % entry] = value
if not blocks:
break
return block
def read_tvips_header(fh, byteorder, dtype, count, offsetsize):
"""Read TVIPS EM-MENU headers and return as dict."""
result = {}
header = fh.read_record(TIFF.TVIPS_HEADER_V1, byteorder=byteorder)
for name, typestr in TIFF.TVIPS_HEADER_V1:
result[name] = header[name].tolist()
if header['Version'] == 2:
header = fh.read_record(TIFF.TVIPS_HEADER_V2, byteorder=byteorder)
if header['Magic'] != int(0xaaaaaaaa):
warnings.warn("invalid TVIPS v2 magic number")
return {}
# decode utf16 strings
for name, typestr in TIFF.TVIPS_HEADER_V2:
if typestr.startswith('V'):
s = header[name].tostring().decode('utf16', errors='ignore')
result[name] = stripnull(s, null='\0')
else:
result[name] = header[name].tolist()
# convert nm to m
for axis in 'XY':
header['PhysicalPixelSize' + axis] /= 1e9
header['PixelSize' + axis] /= 1e9
elif header.version != 1:
warnings.warn("unknown TVIPS header version")
return {}
return result
def read_fei_metadata(fh, byteorder, dtype, count, offsetsize):
"""Read FEI SFEG/HELIOS headers and return as dict."""
result = {}
section = {}
data = bytes2str(fh.read(count))
for line in data.splitlines():
line = line.strip()
if line.startswith('['):
section = {}
result[line[1:-1]] = section
continue
try:
key, value = line.split('=')
except ValueError:
continue
section[key] = astype(value)
return result
def read_cz_sem(fh, byteorder, dtype, count, offsetsize):
"""Read Zeiss SEM tag and return as dict."""
result = {'': ()}
key = None
data = bytes2str(fh.read(count))
for line in data.splitlines():
if line.isupper():
key = line.lower()
elif key:
try:
name, value = line.split('=')
except ValueError:
continue
value = value.strip()
unit = ''
try:
v, u = value.split()
number = astype(v, (int, float))
if number != v:
value = number
unit = u
except Exception:
number = astype(value, (int, float))
if number != value:
value = number
if value in ('No', 'Off'):
value = False
elif value in ('Yes', 'On'):
value = True
result[key] = (name.strip(), value)
if unit:
result[key] += (unit,)
key = None
else:
result[''] += (astype(line, (int, float)),)
return result
def read_nih_image_header(fh, byteorder, dtype, count, offsetsize):
"""Read NIH_IMAGE_HEADER tag from file and return as dict."""
a = fh.read_record(TIFF.NIH_IMAGE_HEADER, byteorder=byteorder)
a = a.newbyteorder(byteorder)
a = recarray2dict(a)
a['XUnit'] = a['XUnit'][:a['XUnitSize']]
a['UM'] = a['UM'][:a['UMsize']]
return a
def read_scanimage_metadata(fh):
"""Read ScanImage BigTIFF v3 static and ROI metadata from open file.
Return non-varying frame data as dict and ROI group data as JSON.
The settings can be used to read image data and metadata without parsing
the TIFF file.
Raise ValueError if file does not contain valid ScanImage v3 metadata.
"""
fh.seek(0)
try:
byteorder, version = struct.unpack('<2sH', fh.read(4))
if byteorder != b'II' or version != 43:
raise Exception
fh.seek(16)
magic, version, size0, size1 = struct.unpack('<IIII', fh.read(16))
if magic != 117637889 or version != 3:
raise Exception
except Exception:
raise ValueError("not a ScanImage BigTIFF v3 file")
frame_data = matlabstr2py(bytes2str(fh.read(size0)[:-1]))
roi_data = read_json(fh, '<', None, size1, None)
return frame_data, roi_data
def read_micromanager_metadata(fh):
"""Read MicroManager non-TIFF settings from open file and return as dict.
The settings can be used to read image data without parsing the TIFF file.
Raise ValueError if the file does not contain valid MicroManager metadata.
"""
fh.seek(0)
try:
byteorder = {b'II': '<', b'MM': '>'}[fh.read(2)]
except IndexError:
raise ValueError("not a MicroManager TIFF file")
result = {}
fh.seek(8)
(index_header, index_offset, display_header, display_offset,
comments_header, comments_offset, summary_header, summary_length
) = struct.unpack(byteorder + "IIIIIIII", fh.read(32))
if summary_header != 2355492:
raise ValueError("invalid MicroManager summary header")
result['Summary'] = read_json(fh, byteorder, None, summary_length, None)
if index_header != 54773648:
raise ValueError("invalid MicroManager index header")
fh.seek(index_offset)
header, count = struct.unpack(byteorder + "II", fh.read(8))
if header != 3453623:
raise ValueError("invalid MicroManager index header")
data = struct.unpack(byteorder + "IIIII"*count, fh.read(20*count))
result['IndexMap'] = {'Channel': data[::5],
'Slice': data[1::5],
'Frame': data[2::5],
'Position': data[3::5],
'Offset': data[4::5]}
if display_header != 483765892:
raise ValueError("invalid MicroManager display header")
fh.seek(display_offset)
header, count = struct.unpack(byteorder + "II", fh.read(8))
if header != 347834724:
raise ValueError("invalid MicroManager display header")
result['DisplaySettings'] = read_json(fh, byteorder, None, count, None)
if comments_header != 99384722:
raise ValueError("invalid MicroManager comments header")
fh.seek(comments_offset)
header, count = struct.unpack(byteorder + "II", fh.read(8))
if header != 84720485:
raise ValueError("invalid MicroManager comments header")
result['Comments'] = read_json(fh, byteorder, None, count, None)
return result
def read_metaseries_catalog(fh):
"""Read MetaSeries non-TIFF hint catalog from file.
Raise ValueError if the file does not contain a valid hint catalog.
"""
# TODO: implement read_metaseries_catalog
raise NotImplementedError()
def imagej_metadata(data, bytecounts, byteorder):
"""Return IJMetadata tag value as dict.
The 'info' string can have multiple formats, e.g. OIF or ScanImage,
that might be parsed into dicts using the matlabstr2py or
oiffile.SettingsFile functions.
"""
def readstring(data, byteorder):
return data.decode('utf-16' + {'>': 'be', '<': 'le'}[byteorder])
def readdouble(data, byteorder):
return struct.unpack(byteorder+('d' * (len(data) // 8)), data)
def readbytes(data, byteorder):
return numpy.fromstring(data, 'uint8')
metadata_types = { # big endian
b'info': ('Info', readstring),
b'labl': ('Labels', readstring),
b'rang': ('Ranges', readdouble),
b'luts': ('LUTs', readbytes),
b'roi ': ('ROI', readbytes),
b'over': ('Overlays', readbytes)}
metadata_types.update( # little endian
dict((k[::-1], v) for k, v in metadata_types.items()))
if not bytecounts:
raise ValueError("no ImageJ metadata")
if not data[:4] in (b'IJIJ', b'JIJI'):
raise ValueError("invalid ImageJ metadata")
header_size = bytecounts[0]
if header_size < 12 or header_size > 804:
raise ValueError("invalid ImageJ metadata header size")
ntypes = (header_size - 4) // 8
header = struct.unpack(byteorder+'4sI'*ntypes, data[4:4+ntypes*8])
pos = 4 + ntypes * 8
counter = 0
result = {}
for mtype, count in zip(header[::2], header[1::2]):
values = []
name, func = metadata_types.get(mtype, (bytes2str(mtype), read_bytes))
for _ in range(count):
counter += 1
pos1 = pos + bytecounts[counter]
values.append(func(data[pos:pos1], byteorder))
pos = pos1
result[name.strip()] = values[0] if count == 1 else values
return result
def imagej_description_metadata(description):
"""Return metatata from ImageJ image description as dict.
Raise ValueError if not a valid ImageJ description.
>>> description = 'ImageJ=1.11a\\nimages=510\\nhyperstack=true\\n'
>>> imagej_description_metadata(description) # doctest: +SKIP
{'ImageJ': '1.11a', 'images': 510, 'hyperstack': True}
"""
def _bool(val):
return {'true': True, 'false': False}[val.lower()]
result = {}
for line in description.splitlines():
try:
key, val = line.split('=')
except Exception:
continue
key = key.strip()
val = val.strip()
for dtype in (int, float, _bool):
try:
val = dtype(val)
break
except Exception:
pass
result[key] = val
if 'ImageJ' not in result:
raise ValueError("not a ImageJ image description")
return result
def imagej_description(shape, rgb=None, colormaped=False, version='1.11a',
hyperstack=None, mode=None, loop=None, **kwargs):
"""Return ImageJ image description from data shape.
ImageJ can handle up to 6 dimensions in order TZCYXS.
>>> imagej_description((51, 5, 2, 196, 171)) # doctest: +SKIP
ImageJ=1.11a
images=510
channels=2
slices=5
frames=51
hyperstack=true
mode=grayscale
loop=false
"""
if colormaped:
raise NotImplementedError("ImageJ colormapping not supported")
shape = imagej_shape(shape, rgb=rgb)
rgb = shape[-1] in (3, 4)
result = ['ImageJ=%s' % version]
append = []
result.append('images=%i' % product(shape[:-3]))
if hyperstack is None:
hyperstack = True
append.append('hyperstack=true')
else:
append.append('hyperstack=%s' % bool(hyperstack))
if shape[2] > 1:
result.append('channels=%i' % shape[2])
if mode is None and not rgb:
mode = 'grayscale'
if hyperstack and mode:
append.append('mode=%s' % mode)
if shape[1] > 1:
result.append('slices=%i' % shape[1])
if shape[0] > 1:
result.append("frames=%i" % shape[0])
if loop is None:
append.append('loop=false')
if loop is not None:
append.append('loop=%s' % bool(loop))
for key, value in kwargs.items():
append.append('%s=%s' % (key.lower(), value))
return '\n'.join(result + append + [''])
def imagej_shape(shape, rgb=None):
"""Return shape normalized to 6D ImageJ hyperstack TZCYXS.
Raise ValueError if not a valid ImageJ hyperstack shape.
>>> imagej_shape((2, 3, 4, 5, 3), False)
(2, 3, 4, 5, 3, 1)
"""
shape = tuple(int(i) for i in shape)
ndim = len(shape)
if 1 > ndim > 6:
raise ValueError("invalid ImageJ hyperstack: not 2 to 6 dimensional")
if rgb is None:
rgb = shape[-1] in (3, 4) and ndim > 2
if rgb and shape[-1] not in (3, 4):
raise ValueError("invalid ImageJ hyperstack: not a RGB image")
if not rgb and ndim == 6 and shape[-1] != 1:
raise ValueError("invalid ImageJ hyperstack: not a non-RGB image")
if rgb or shape[-1] == 1:
return (1, ) * (6 - ndim) + shape
return (1, ) * (5 - ndim) + shape + (1,)
def json_description(shape, **metadata):
"""Return JSON image description from data shape and other meta data.
Return UTF-8 encoded JSON.
>>> json_description((256, 256, 3), axes='YXS') # doctest: +SKIP
b'{"shape": [256, 256, 3], "axes": "YXS"}'
"""
metadata.update(shape=shape)
return json.dumps(metadata) # .encode('utf-8')
def json_description_metadata(description):
"""Return metatata from JSON formated image description as dict.
Raise ValuError if description is of unknown format.
>>> description = '{"shape": [256, 256, 3], "axes": "YXS"}'
>>> json_description_metadata(description) # doctest: +SKIP
{'shape': [256, 256, 3], 'axes': 'YXS'}
>>> json_description_metadata('shape=(256, 256, 3)')
{'shape': (256, 256, 3)}
"""
if description[:6] == 'shape=':
# old style 'shaped' description; not JSON
shape = tuple(int(i) for i in description[7:-1].split(','))
return dict(shape=shape)
if description[:1] == '{' and description[-1:] == '}':
# JSON description
return json.loads(description)
raise ValueError("invalid JSON image description", description)
def fluoview_description_metadata(description, ignoresections=None):
"""Return metatata from FluoView image description as dict.
The FluoView image description format is unspecified. Expect failures.
>>> descr = ('[Intensity Mapping]\\nMap Ch0: Range=00000 to 02047\\n'
... '[Intensity Mapping End]')
>>> fluoview_description_metadata(descr)
{'Intensity Mapping': {'Map Ch0: Range': '00000 to 02047'}}
"""
if not description.startswith('['):
raise ValueError("invalid FluoView image description")
if ignoresections is None:
ignoresections = {'Region Info (Fields)', 'Protocol Description'}
result = {}
sections = [result]
comment = False
for line in description.splitlines():
if not comment:
line = line.strip()
if not line:
continue
if line[0] == '[':
if line[-5:] == ' End]':
# close section
del sections[-1]
section = sections[-1]
name = line[1:-5]
if comment:
section[name] = '\n'.join(section[name])
if name[:4] == 'LUT ':
a = numpy.array(section[name], dtype='uint8')
a.shape = -1, 3
section[name] = a
continue
# new section
comment = False
name = line[1:-1]
if name[:4] == 'LUT ':
section = []
elif name in ignoresections:
section = []
comment = True
else:
section = {}
sections.append(section)
result[name] = section
continue
# add entry
if comment:
section.append(line)
continue
line = line.split('=', 1)
if len(line) == 1:
section[line[0].strip()] = None
continue
key, value = line
if key[:4] == 'RGB ':
section.extend(int(rgb) for rgb in value.split())
else:
section[key.strip()] = astype(value.strip())
return result
def pilatus_description_metadata(description):
"""Return metatata from Pilatus image description as dict.
Return metadata from Pilatus pixel array detectors by Dectris, created
by camserver or TVX software.
>>> pilatus_description_metadata('# Pixel_size 172e-6 m x 172e-6 m')
{'Pixel_size': (0.000172, 0.000172)}
"""
result = {}
if not description.startswith('# '):
return result
for c in '#:=,()':
description = description.replace(c, ' ')
for line in description.split('\n'):
if line[:2] != ' ':
continue
line = line.split()
name = line[0]
if line[0] not in TIFF.PILATUS_HEADER:
try:
result['DateTime'] = datetime.datetime.strptime(
' '.join(line), '%Y-%m-%dT%H %M %S.%f')
except Exception:
result[name] = ' '.join(line[1:])
continue
indices, dtype = TIFF.PILATUS_HEADER[line[0]]
if isinstance(indices[0], slice):
# assumes one slice
values = line[indices[0]]
else:
values = [line[i] for i in indices]
if dtype is float and values[0] == 'not':
values = ['NaN']
values = tuple(dtype(v) for v in values)
if dtype == str:
values = ' '.join(values)
elif len(values) == 1:
values = values[0]
result[name] = values
return result
def svs_description_metadata(description):
"""Return metatata from Aperio image description as dict.
The Aperio image description format is unspecified. Expect failures.
>>> svs_description_metadata('Aperio Image Library v1.0')
{'Aperio Image Library': 'v1.0'}
"""
if not description.startswith('Aperio Image Library '):
raise ValueError("invalid Aperio image description")
result = {}
lines = description.split('\n')
key, value = lines[0].strip().rsplit(None, 1) # 'Aperio Image Library'
result[key.strip()] = value.strip()
if len(lines) == 1:
return result
items = lines[1].split('|')
result[''] = items[0].strip() # TODO: parse this?
for item in items[1:]:
key, value = item.split(' = ')
result[key.strip()] = astype(value.strip())
return result
def stk_description_metadata(description):
"""Return metadata from MetaMorph image description as list of dict.
The MetaMorph image description format is unspecified. Expect failures.
"""
description = description.strip()
if not description:
return []
try:
description = bytes2str(description)
except UnicodeDecodeError:
warnings.warn("failed to parse MetaMorph image description")
return []
result = []
for plane in description.split('\x00'):
d = {}
for line in plane.split('\r\n'):
line = line.split(':', 1)
if len(line) > 1:
name, value = line
d[name.strip()] = astype(value.strip())
else:
value = line[0].strip()
if value:
if '' in d:
d[''].append(value)
else:
d[''] = [value]
result.append(d)
return result
def metaseries_description_metadata(description):
"""Return metatata from MetaSeries image description as dict."""
if not description.startswith('<MetaData>'):
raise ValueError("invalid MetaSeries image description")
from xml.etree import cElementTree as etree # delayed import
root = etree.fromstring(description)
types = {'float': float, 'int': int,
'bool': lambda x: asbool(x, 'on', 'off')}
def parse(root, result):
# recursive
for child in root:
attrib = child.attrib
if not attrib:
result[child.tag] = parse(child, {})
continue
if 'id' in attrib:
i = attrib['id']
t = attrib['type']
v = attrib['value']
if t in types:
result[i] = types[t](v)
else:
result[i] = v
return result
adict = parse(root, {})
if 'Description' in adict:
adict['Description'] = adict['Description'].replace(' ', '\n')
return adict
def scanimage_description_metadata(description):
"""Return metatata from ScanImage image description as dict."""
return matlabstr2py(description)
def scanimage_artist_metadata(artist):
"""Return metatata from ScanImage artist tag as dict."""
try:
return json.loads(artist)
except ValueError:
warnings.warn("invalid JSON '%s'" % artist)
def _replace_by(module_function, package=__package__, warn=None, prefix='_'):
"""Try replace decorated function by module.function."""
def _warn(e, warn):
if warn is None:
warn = "\n Functionality might be degraded or be slow.\n"
elif warn is True:
warn = ''
elif not warn:
return
warnings.warn("%s%s" % (e, warn))
try:
from importlib import import_module
except ImportError as e:
_warn(e, warn)
return identityfunc
def decorate(func, module_function=module_function, warn=warn):
module, function = module_function.split('.')
try:
if package:
module = import_module('.' + module, package=package)
else:
module = import_module(module)
except Exception as e:
_warn(e, warn)
return func
try:
func, oldfunc = getattr(module, function), func
except Exception as e:
_warn(e, warn)
return func
globals()[prefix + func.__name__] = oldfunc
return func
return decorate
def decode_floats(data):
"""Decode floating point horizontal differencing.
The TIFF predictor type 3 reorders the bytes of the image values and
applies horizontal byte differencing to improve compression of floating
point images. The ordering of interleaved color channels is preserved.
Parameters
----------
data : numpy.ndarray
The image to be decoded. The dtype must be a floating point.
The shape must include the number of contiguous samples per pixel
even if 1.
"""
shape = data.shape
dtype = data.dtype
if len(shape) < 3:
raise ValueError('invalid data shape')
if dtype.char not in 'dfe':
raise ValueError('not a floating point image')
littleendian = data.dtype.byteorder == '<' or (
sys.byteorder == 'little' and data.dtype.byteorder == '=')
# undo horizontal byte differencing
data = data.view('uint8')
data.shape = shape[:-2] + (-1,) + shape[-1:]
numpy.cumsum(data, axis=-2, dtype='uint8', out=data)
# reorder bytes
if littleendian:
data.shape = shape[:-2] + (-1,) + shape[-2:]
data = numpy.swapaxes(data, -3, -2)
data = numpy.swapaxes(data, -2, -1)
data = data[..., ::-1]
# back to float
data = numpy.ascontiguousarray(data)
data = data.view(dtype)
data.shape = shape
return data
def decode_jpeg(encoded, tables=b'', photometric=None,
ycbcrsubsampling=None, ycbcrpositioning=None):
"""Decode JPEG encoded byte string (using _czifile extension module)."""
from czifile import _czifile
image = _czifile.decode_jpeg(encoded, tables)
if photometric == 2 and ycbcrsubsampling and ycbcrpositioning:
# TODO: convert YCbCr to RGB
pass
return image.tostring()
@_replace_by('_tifffile.decode_packbits')
def decode_packbits(encoded):
"""Decompress PackBits encoded byte string.
PackBits is a simple byte-oriented run-length compression scheme.
"""
func = ord if sys.version[0] == '2' else identityfunc
result = []
result_extend = result.extend
i = 0
try:
while True:
n = func(encoded[i]) + 1
i += 1
if n < 129:
result_extend(encoded[i:i+n])
i += n
elif n > 129:
result_extend(encoded[i:i+1] * (258-n))
i += 1
except IndexError:
pass
return b''.join(result) if sys.version[0] == '2' else bytes(result)
@_replace_by('_tifffile.decode_lzw')
def decode_lzw(encoded):
"""Decompress LZW (Lempel-Ziv-Welch) encoded TIFF strip (byte string).
The strip must begin with a CLEAR code and end with an EOI code.
This is an implementation of the LZW decoding algorithm described in (1).
It is not compatible with old style LZW compressed files like quad-lzw.tif.
"""
len_encoded = len(encoded)
bitcount_max = len_encoded * 8
unpack = struct.unpack
if sys.version[0] == '2':
newtable = [chr(i) for i in range(256)]
else:
newtable = [bytes([i]) for i in range(256)]
newtable.extend((0, 0))
def next_code():
"""Return integer of 'bitw' bits at 'bitcount' position in encoded."""
start = bitcount // 8
s = encoded[start:start+4]
try:
code = unpack('>I', s)[0]
except Exception:
code = unpack('>I', s + b'\x00'*(4-len(s)))[0]
code <<= bitcount % 8
code &= mask
return code >> shr
switchbitch = { # code: bit-width, shr-bits, bit-mask
255: (9, 23, int(9*'1'+'0'*23, 2)),
511: (10, 22, int(10*'1'+'0'*22, 2)),
1023: (11, 21, int(11*'1'+'0'*21, 2)),
2047: (12, 20, int(12*'1'+'0'*20, 2)), }
bitw, shr, mask = switchbitch[255]
bitcount = 0
if len_encoded < 4:
raise ValueError("strip must be at least 4 characters long")
if next_code() != 256:
raise ValueError("strip must begin with CLEAR code")
code = 0
oldcode = 0
result = []
result_append = result.append
while True:
code = next_code() # ~5% faster when inlining this function
bitcount += bitw
if code == 257 or bitcount >= bitcount_max: # EOI
break
if code == 256: # CLEAR
table = newtable[:]
table_append = table.append
lentable = 258
bitw, shr, mask = switchbitch[255]
code = next_code()
bitcount += bitw
if code == 257: # EOI
break
result_append(table[code])
else:
if code < lentable:
decoded = table[code]
newcode = table[oldcode] + decoded[:1]
else:
newcode = table[oldcode]
newcode += newcode[:1]
decoded = newcode
result_append(decoded)
table_append(newcode)
lentable += 1
oldcode = code
if lentable in switchbitch:
bitw, shr, mask = switchbitch[lentable]
if code != 257:
warnings.warn("unexpected end of lzw stream (code %i)" % code)
return b''.join(result)
@_replace_by('_tifffile.unpack_ints')
def unpack_ints(data, dtype, itemsize, runlen=0):
"""Decompress byte string to array of integers of any bit size <= 32.
This Python implementation is slow and only handles itemsizes 1, 2, 4, 8,
16, 32, and 64.
Parameters
----------
data : byte str
Data to decompress.
dtype : numpy.dtype or str
A numpy boolean or integer type.
itemsize : int
Number of bits per integer.
runlen : int
Number of consecutive integers, after which to start at next byte.
Examples
--------
>>> unpack_ints(b'a', 'B', 1)
array([0, 1, 1, 0, 0, 0, 0, 1], dtype=uint8)
>>> unpack_ints(b'ab', 'B', 2)
array([1, 2, 0, 1, 1, 2, 0, 2], dtype=uint8)
"""
if itemsize == 1: # bitarray
data = numpy.fromstring(data, '|B')
data = numpy.unpackbits(data)
if runlen % 8:
data = data.reshape(-1, runlen + (8 - runlen % 8))
data = data[:, :runlen].reshape(-1)
return data.astype(dtype)
dtype = numpy.dtype(dtype)
if itemsize in (8, 16, 32, 64):
return numpy.fromstring(data, dtype)
if itemsize not in (1, 2, 4, 8, 16, 32):
raise ValueError("itemsize not supported: %i" % itemsize)
if dtype.kind not in "biu":
raise ValueError("invalid dtype")
itembytes = next(i for i in (1, 2, 4, 8) if 8 * i >= itemsize)
if itembytes != dtype.itemsize:
raise ValueError("dtype.itemsize too small")
if runlen == 0:
runlen = (8 * len(data)) // itemsize
skipbits = runlen * itemsize % 8
if skipbits:
skipbits = 8 - skipbits
shrbits = itembytes*8 - itemsize
bitmask = int(itemsize*'1'+'0'*shrbits, 2)
dtypestr = '>' + dtype.char # dtype always big endian?
unpack = struct.unpack
l = runlen * (len(data)*8 // (runlen*itemsize + skipbits))
result = numpy.empty((l,), dtype)
bitcount = 0
for i in range(l):
start = bitcount // 8
s = data[start:start+itembytes]
try:
code = unpack(dtypestr, s)[0]
except Exception:
code = unpack(dtypestr, s + b'\x00'*(itembytes-len(s)))[0]
code <<= bitcount % 8
code &= bitmask
result[i] = code >> shrbits
bitcount += itemsize
if (i+1) % runlen == 0:
bitcount += skipbits
return result
def unpack_rgb(data, dtype='<B', bitspersample=(5, 6, 5), rescale=True):
"""Return array from byte string containing packed samples.
Use to unpack RGB565 or RGB555 to RGB888 format.
Parameters
----------
data : byte str
The data to be decoded. Samples in each pixel are stored consecutively.
Pixels are aligned to 8, 16, or 32 bit boundaries.
dtype : numpy.dtype
The sample data type. The byteorder applies also to the data stream.
bitspersample : tuple
Number of bits for each sample in a pixel.
rescale : bool
Upscale samples to the number of bits in dtype.
Returns
-------
result : ndarray
Flattened array of unpacked samples of native dtype.
Examples
--------
>>> data = struct.pack('BBBB', 0x21, 0x08, 0xff, 0xff)
>>> print(unpack_rgb(data, '<B', (5, 6, 5), False))
[ 1 1 1 31 63 31]
>>> print(unpack_rgb(data, '<B', (5, 6, 5)))
[ 8 4 8 255 255 255]
>>> print(unpack_rgb(data, '<B', (5, 5, 5)))
[ 16 8 8 255 255 255]
"""
dtype = numpy.dtype(dtype)
bits = int(numpy.sum(bitspersample))
if not (bits <= 32 and all(i <= dtype.itemsize*8 for i in bitspersample)):
raise ValueError("sample size not supported %s" % str(bitspersample))
dt = next(i for i in 'BHI' if numpy.dtype(i).itemsize*8 >= bits)
data = numpy.fromstring(data, dtype.byteorder+dt)
result = numpy.empty((data.size, len(bitspersample)), dtype.char)
for i, bps in enumerate(bitspersample):
t = data >> int(numpy.sum(bitspersample[i+1:]))
t &= int('0b'+'1'*bps, 2)
if rescale:
o = ((dtype.itemsize * 8) // bps + 1) * bps
if o > data.dtype.itemsize * 8:
t = t.astype('I')
t *= (2**o - 1) // (2**bps - 1)
t //= 2**(o - (dtype.itemsize * 8))
result[:, i] = t
return result.reshape(-1)
@_replace_by('_tifffile.reverse_bitorder')
def reverse_bitorder(data):
"""Reverse bits in each byte of byte string or numpy array.
Decode data where pixels with lower column values are stored in the
lower-order bits of the bytes (FillOrder is LSB2MSB).
Parameters
----------
data : byte string or ndarray
The data to be bit reversed. If byte string, a new bit-reversed byte
string is returned. Numpy arrays are bit-reversed in-place.
Examples
--------
>>> reverse_bitorder(b'\\x01\\x64')
b'\\x80&'
>>> data = numpy.array([1, 666], dtype='uint16')
>>> reverse_bitorder(data)
>>> data
array([ 128, 16473], dtype=uint16)
"""
try:
view = data.view('uint8')
numpy.take(TIFF.REVERSE_BITORDER_ARRAY, view, out=view)
except AttributeError:
return data.translate(TIFF.REVERSE_BITORDER_BYTES)
except ValueError:
raise NotImplementedError("slices of arrays not supported")
def apply_colormap(image, colormap, contig=True):
"""Return palette-colored image.
The image values are used to index the colormap on axis 1. The returned
image is of shape image.shape+colormap.shape[0] and dtype colormap.dtype.
Parameters
----------
image : numpy.ndarray
Indexes into the colormap.
colormap : numpy.ndarray
RGB lookup table aka palette of shape (3, 2**bits_per_sample).
contig : bool
If True, return a contiguous array.
Examples
--------
>>> image = numpy.arange(256, dtype='uint8')
>>> colormap = numpy.vstack([image, image, image]).astype('uint16') * 256
>>> apply_colormap(image, colormap)[-1]
array([65280, 65280, 65280], dtype=uint16)
"""
image = numpy.take(colormap, image, axis=1)
image = numpy.rollaxis(image, 0, image.ndim)
if contig:
image = numpy.ascontiguousarray(image)
return image
def reorient(image, orientation):
"""Return reoriented view of image array.
Parameters
----------
image : numpy.ndarray
Non-squeezed output of asarray() functions.
Axes -3 and -2 must be image length and width respectively.
orientation : int or str
One of TIFF.ORIENTATION names or values.
"""
ORIENTATION = TIFF.ORIENTATION
orientation = enumarg(ORIENTATION, orientation)
if orientation == ORIENTATION.TOPLEFT:
return image
elif orientation == ORIENTATION.TOPRIGHT:
return image[..., ::-1, :]
elif orientation == ORIENTATION.BOTLEFT:
return image[..., ::-1, :, :]
elif orientation == ORIENTATION.BOTRIGHT:
return image[..., ::-1, ::-1, :]
elif orientation == ORIENTATION.LEFTTOP:
return numpy.swapaxes(image, -3, -2)
elif orientation == ORIENTATION.RIGHTTOP:
return numpy.swapaxes(image, -3, -2)[..., ::-1, :]
elif orientation == ORIENTATION.RIGHTBOT:
return numpy.swapaxes(image, -3, -2)[..., ::-1, :, :]
elif orientation == ORIENTATION.LEFTBOT:
return numpy.swapaxes(image, -3, -2)[..., ::-1, ::-1, :]
def repeat_nd(a, repeats):
"""Return read-only view into input array with elements repeated.
Zoom nD image by integer factors using nearest neighbor interpolation
(box filter).
Parameters
----------
a : array_like
Input array.
repeats : sequence of int
The number of repetitions to apply along each dimension of input array.
Example
-------
>>> repeat_nd([[1, 2], [3, 4]], (2, 2))
array([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 3, 4, 4],
[3, 3, 4, 4]])
"""
a = numpy.asarray(a)
reshape = []
shape = []
strides = []
for i, j, k in zip(a.strides, a.shape, repeats):
shape.extend((j, k))
strides.extend((i, 0))
reshape.append(j * k)
return numpy.lib.stride_tricks.as_strided(
a, shape, strides, writeable=False).reshape(reshape)
def reshape_nd(data_or_shape, ndim):
"""Return image array or shape with at least ndim dimensions.
Prepend 1s to image shape as necessary.
>>> reshape_nd(numpy.empty(0), 1).shape
(0,)
>>> reshape_nd(numpy.empty(1), 2).shape
(1, 1)
>>> reshape_nd(numpy.empty((2, 3)), 3).shape
(1, 2, 3)
>>> reshape_nd(numpy.empty((3, 4, 5)), 3).shape
(3, 4, 5)
>>> reshape_nd((2, 3), 3)
(1, 2, 3)
"""
is_shape = isinstance(data_or_shape, tuple)
shape = data_or_shape if is_shape else data_or_shape.shape
if len(shape) >= ndim:
return data_or_shape
shape = (1,) * (ndim - len(shape)) + shape
return shape if is_shape else data_or_shape.reshape(shape)
def squeeze_axes(shape, axes, skip='XY'):
"""Return shape and axes with single-dimensional entries removed.
Remove unused dimensions unless their axes are listed in 'skip'.
>>> squeeze_axes((5, 1, 2, 1, 1), 'TZYXC')
((5, 2, 1), 'TYX')
"""
if len(shape) != len(axes):
raise ValueError("dimensions of axes and shape do not match")
shape, axes = zip(*(i for i in zip(shape, axes)
if i[0] > 1 or i[1] in skip))
return tuple(shape), ''.join(axes)
def transpose_axes(image, axes, asaxes='CTZYX'):
"""Return image with its axes permuted to match specified axes.
A view is returned if possible.
>>> transpose_axes(numpy.zeros((2, 3, 4, 5)), 'TYXC', asaxes='CTZYX').shape
(5, 2, 1, 3, 4)
"""
for ax in axes:
if ax not in asaxes:
raise ValueError("unknown axis %s" % ax)
# add missing axes to image
shape = image.shape
for ax in reversed(asaxes):
if ax not in axes:
axes = ax + axes
shape = (1,) + shape
image = image.reshape(shape)
# transpose axes
image = image.transpose([axes.index(ax) for ax in asaxes])
return image
def reshape_axes(axes, shape, newshape, unknown='Q'):
"""Return axes matching new shape.
Unknown dimensions are labelled 'Q'.
>>> reshape_axes('YXS', (219, 301, 1), (219, 301))
'YX'
>>> reshape_axes('IYX', (12, 219, 301), (3, 4, 219, 1, 301, 1))
'QQYQXQ'
"""
shape = tuple(shape)
newshape = tuple(newshape)
if len(axes) != len(shape):
raise ValueError("axes do not match shape")
size = product(shape)
newsize = product(newshape)
if size != newsize:
raise ValueError("can not reshape %s to %s" % (shape, newshape))
if not axes or not newshape:
return ''
lendiff = max(0, len(shape) - len(newshape))
if lendiff:
newshape = newshape + (1,) * lendiff
i = len(shape)-1
prodns = 1
prods = 1
result = []
for ns in newshape[::-1]:
prodns *= ns
while i > 0 and shape[i] == 1 and ns != 1:
i -= 1
if ns == shape[i] and prodns == prods*shape[i]:
prods *= shape[i]
result.append(axes[i])
i -= 1
else:
result.append(unknown)
return ''.join(reversed(result[lendiff:]))
def stack_pages(pages, out=None, maxworkers=1, *args, **kwargs):
"""Read data from sequence of TiffPage and stack them vertically.
Additional parameters are passsed to the TiffPage.asarray function.
"""
npages = len(pages)
if npages == 0:
raise ValueError("no pages")
if npages == 1:
return pages[0].asarray(out=out, *args, **kwargs)
page0 = next(p for p in pages if p is not None)
page0.asarray(validate=None) # ThreadPoolExecutor swallows exceptions
shape = (npages,) + page0.keyframe.shape
dtype = page0.keyframe.dtype
out = create_output(out, shape, dtype)
if maxworkers is None:
maxworkers = multiprocessing.cpu_count() // 2
page0.parent.filehandle.lock = maxworkers > 1
filecache = OpenFileCache(size=max(4, maxworkers),
lock=page0.parent.filehandle.lock)
def func(page, index, out=out, filecache=filecache,
args=args, kwargs=kwargs):
"""Read, decode, and copy page data."""
if page is not None:
filecache.open(page.parent.filehandle)
out[index] = page.asarray(lock=filecache.lock, reopen=False,
validate=False, *args, **kwargs)
filecache.close(page.parent.filehandle)
if maxworkers < 2:
for i, page in enumerate(pages):
func(page, i)
else:
with concurrent.futures.ThreadPoolExecutor(maxworkers) as executor:
executor.map(func, pages, range(npages))
filecache.clear()
page0.parent.filehandle.lock = None
return out
def clean_offsets_counts(offsets, counts):
"""Return cleaned offsets and byte counts.
Remove zero offsets and counts. Use to sanitize _offsets and _bytecounts
tag values for strips or tiles.
"""
offsets = list(offsets)
counts = list(counts)
assert len(offsets) == len(counts)
j = 0
for i, (o, b) in enumerate(zip(offsets, counts)):
if o > 0 and b > 0:
if i > j:
offsets[j] = o
counts[j] = b
j += 1
elif b > 0 and o <= 0:
raise ValueError("invalid offset")
else:
warnings.warn("empty byte count")
if j == 0:
j = 1
return offsets[:j], counts[:j]
def buffered_read(fh, lock, offsets, bytecounts, buffersize=2**26):
"""Return iterator over blocks read from file."""
length = len(offsets)
i = 0
while i < length:
data = []
with lock:
size = 0
while size < buffersize and i < length:
fh.seek(offsets[i])
bytecount = bytecounts[i]
data.append(fh.read(bytecount))
size += bytecount
i += 1
for block in data:
yield block
def create_output(out, shape, dtype, mode='w+', suffix='.memmap'):
"""Return numpy array where image data of shape and dtype can copied.
The 'out' parameter may have the following values or types:
None
An empty array of shape and dtype is created and returned.
numpy.ndarray
An existing writable array of compatible dtype and shape. A view of
the same array is returned after verification.
'memmap' or 'memmap:tempdir'
A memory-map to an array stored in a temporary binary file on disk
is created and returned.
str or open file
The file name or file object used to create a memory-map to an array
stored in a binary file on disk. The created memory-mapped array is
returned.
"""
if out is None:
return numpy.zeros(shape, dtype)
if isinstance(out, str) and out[:6] == 'memmap':
tempdir = out[7:] if len(out) > 7 else None
with tempfile.NamedTemporaryFile(dir=tempdir, suffix=suffix) as fh:
return numpy.memmap(fh, shape=shape, dtype=dtype, mode=mode)
if isinstance(out, numpy.ndarray):
if product(shape) != product(out.shape):
raise ValueError("incompatible output shape")
if not numpy.can_cast(dtype, out.dtype):
raise ValueError("incompatible output dtype")
return out.reshape(shape)
return numpy.memmap(out, shape=shape, dtype=dtype, mode=mode)
def matlabstr2py(s):
"""Return Python object from Matlab string representation.
Return str, bool, int, float, list (Matlab arrays or cells), or
dict (Matlab structures) types.
Use to access ScanImage metadata.
>>> matlabstr2py('1')
1
>>> matlabstr2py("['x y z' true false; 1 2.0 -3e4; NaN Inf @class]")
[['x y z', True, False], [1, 2.0, -30000.0], [nan, inf, '@class']]
>>> d = matlabstr2py("SI.hChannels.channelType = {'stripe' 'stripe'}\\n"
... "SI.hChannels.channelsActive = 2")
>>> d['SI.hChannels.channelType']
['stripe', 'stripe']
"""
# TODO: handle invalid input
# TODO: review unboxing of multidimensional arrays
def lex(s):
# return sequence of tokens from matlab string representation
tokens = ['[']
while True:
t, i = next_token(s)
if t is None:
break
if t == ';':
tokens.extend((']', '['))
elif t == '[':
tokens.extend(('[', '['))
elif t == ']':
tokens.extend((']', ']'))
else:
tokens.append(t)
s = s[i:]
tokens.append(']')
return tokens
def next_token(s):
# return next token in matlab string
length = len(s)
if length == 0:
return None, 0
i = 0
while i < length and s[i] == ' ':
i += 1
if i == length:
return None, i
if s[i] in '{[;]}':
return s[i], i + 1
if s[i] == "'":
j = i + 1
while j < length and s[j] != "'":
j += 1
return s[i: j+1], j + 1
j = i
while j < length and not s[j] in ' {[;]}':
j += 1
return s[i:j], j
def value(s, fail=False):
# return Python value of token
s = s.strip()
if not s:
return s
if len(s) == 1:
try:
return int(s)
except Exception:
if fail:
raise ValueError()
return s
if s[0] == "'":
if fail and s[-1] != "'" or "'" in s[1:-1]:
raise ValueError()
return s[1:-1]
if fail and any(i in s for i in " ';[]{}"):
raise ValueError()
if s[0] == '@':
return s
if s == 'true':
return True
if s == 'false':
return False
if '.' in s or 'e' in s:
return float(s)
try:
return int(s)
except Exception:
pass
try:
return float(s) # nan, inf
except Exception:
if fail:
raise ValueError()
return s
def parse(s):
# return Python value from string representation of Matlab value
s = s.strip()
try:
return value(s, fail=True)
except ValueError:
pass
result = add2 = []
levels = [add2]
for t in lex(s):
if t in '[{':
add2 = []
levels.append(add2)
elif t in ']}':
x = levels.pop()
if len(x) == 1 and isinstance(x[0], list):
x = x[0]
add2 = levels[-1]
add2.append(x)
else:
add2.append(value(t))
if len(result) == 1 and isinstance(result[0], list):
result = result[0]
return result
if '\r' in s or '\n' in s:
# structure
d = {}
for line in s.splitlines():
if not line.strip():
continue
k, v = line.split('=', 1)
k = k.strip()
if any(c in k for c in " ';[]{}"):
continue
d[k] = parse(v.strip())
return d
return parse(s)
def stripnull(string, null=b'\x00'):
"""Return string truncated at first null character.
Clean NULL terminated C strings. For unicode strings use null='\\0'.
>>> stripnull(b'string\\x00')
b'string'
>>> stripnull('string\\x00', null='\\0')
'string'
"""
i = string.find(null)
return string if (i < 0) else string[:i]
def stripascii(string):
"""Return string truncated at last byte that is 7-bit ASCII.
Clean NULL separated and terminated TIFF strings.
>>> stripascii(b'string\\x00string\\n\\x01\\x00')
b'string\\x00string\\n'
>>> stripascii(b'\\x00')
b''
"""
# TODO: pythonize this
i = len(string)
while i:
i -= 1
if 8 < byte2int(string[i]) < 127:
break
else:
i = -1
return string[:i+1]
def asbool(value, true=(b'true', u'true'), false=(b'false', u'false')):
"""Return string as bool if possible, else raise TypeError.
>>> asbool(b' False ')
False
"""
value = value.strip().lower()
if value in true: # might raise UnicodeWarning/BytesWarning
return True
if value in false:
return False
raise TypeError()
def astype(value, types=None):
"""Return argument as one of types if possible.
>>> astype('42')
42
>>> astype('3.14')
3.14
>>> astype('True')
True
>>> astype(b'Neee-Wom')
'Neee-Wom'
"""
if types is None:
types = int, float, asbool, bytes2str
for typ in types:
try:
return typ(value)
except (ValueError, AttributeError, TypeError, UnicodeEncodeError):
pass
return value
def format_size(size, threshold=1536):
"""Return file size as string from byte size.
>>> format_size(1234)
'1234 B'
>>> format_size(12345678901)
'11.50 GiB'
"""
if size < threshold:
return "%i B" % size
for unit in ('KiB', 'MiB', 'GiB', 'TiB', 'PiB'):
size /= 1024.0
if size < threshold:
return "%.2f %s" % (size, unit)
def identityfunc(arg):
"""Single argument identity function.
>>> identityfunc('arg')
'arg'
"""
return arg
def nullfunc(*args, **kwargs):
"""Null function.
>>> nullfunc('arg', kwarg='kwarg')
"""
return
def sequence(value):
"""Return tuple containing value if value is not a sequence.
>>> sequence(1)
(1,)
>>> sequence([1])
[1]
"""
try:
len(value)
return value
except TypeError:
return (value,)
def product(iterable):
"""Return product of sequence of numbers.
Equivalent of functools.reduce(operator.mul, iterable, 1).
Multiplying numpy integers might overflow.
>>> product([2**8, 2**30])
274877906944
>>> product([])
1
"""
prod = 1
for i in iterable:
prod *= i
return prod
def natural_sorted(iterable):
"""Return human sorted list of strings.
E.g. for sorting file names.
>>> natural_sorted(['f1', 'f2', 'f10'])
['f1', 'f2', 'f10']
"""
def sortkey(x):
return [(int(c) if c.isdigit() else c) for c in re.split(numbers, x)]
numbers = re.compile(r'(\d+)')
return sorted(iterable, key=sortkey)
def excel_datetime(timestamp, epoch=datetime.datetime.fromordinal(693594)):
"""Return datetime object from timestamp in Excel serial format.
Convert LSM time stamps.
>>> excel_datetime(40237.029999999795)
datetime.datetime(2010, 2, 28, 0, 43, 11, 999982)
"""
return epoch + datetime.timedelta(timestamp)
def julian_datetime(julianday, milisecond=0):
"""Return datetime from days since 1/1/4713 BC and ms since midnight.
Convert Julian dates according to MetaMorph.
>>> julian_datetime(2451576, 54362783)
datetime.datetime(2000, 2, 2, 15, 6, 2, 783)
"""
if julianday <= 1721423:
# no datetime before year 1
return None
a = julianday + 1
if a > 2299160:
alpha = math.trunc((a - 1867216.25) / 36524.25)
a += 1 + alpha - alpha // 4
b = a + (1524 if a > 1721423 else 1158)
c = math.trunc((b - 122.1) / 365.25)
d = math.trunc(365.25 * c)
e = math.trunc((b - d) / 30.6001)
day = b - d - math.trunc(30.6001 * e)
month = e - (1 if e < 13.5 else 13)
year = c - (4716 if month > 2.5 else 4715)
hour, milisecond = divmod(milisecond, 1000 * 60 * 60)
minute, milisecond = divmod(milisecond, 1000 * 60)
second, milisecond = divmod(milisecond, 1000)
return datetime.datetime(year, month, day,
hour, minute, second, milisecond)
def byteorder_isnative(byteorder):
"""Return if byteorder matches the system's byteorder.
>>> byteorder_isnative('=')
True
"""
if byteorder == '=' or byteorder == sys.byteorder:
return True
keys = {'big': '>', 'little': '<'}
return keys.get(byteorder, byteorder) == keys[sys.byteorder]
def recarray2dict(recarray):
"""Return numpy.recarray as dict."""
# TODO: subarrays
result = {}
for descr, value in zip(recarray.dtype.descr, recarray):
name, dtype = descr[:2]
if dtype[1] == 'S':
value = bytes2str(stripnull(value))
elif value.ndim < 2:
value = value.tolist()
result[name] = value
return result
def xml2dict(xml, sanitize=True, prefix=None):
"""Return XML as dict.
>>> xml2dict('<?xml version="1.0" ?><root attr="name"><key>1</key></root>')
{'root': {'key': 1, 'attr': 'name'}}
"""
from collections import defaultdict # delayed import
from xml.etree import cElementTree as etree # delayed import
at = tx = ''
if prefix:
at, tx = prefix
def astype(value):
# return value as int, float, bool, or str
for t in (int, float, asbool):
try:
return t(value)
except Exception:
pass
return value
def etree2dict(t):
# adapted from https://stackoverflow.com/a/10077069/453463
key = t.tag
if sanitize:
key = key.rsplit('}', 1)[-1]
d = {key: {} if t.attrib else None}
children = list(t)
if children:
dd = defaultdict(list)
for dc in map(etree2dict, children):
for k, v in dc.items():
dd[k].append(astype(v))
d = {key: {k: astype(v[0]) if len(v) == 1 else astype(v)
for k, v in dd.items()}}
if t.attrib:
d[key].update((at + k, astype(v)) for k, v in t.attrib.items())
if t.text:
text = t.text.strip()
if children or t.attrib:
if text:
d[key][tx + 'value'] = astype(text)
else:
d[key] = astype(text)
return d
return etree2dict(etree.fromstring(xml))
def pformat_xml(arg):
"""Return pretty formatted XML."""
try:
import lxml.etree as etree # delayed import
if not isinstance(arg, bytes):
arg = arg.encode('utf-8')
xml = etree.fromstring(arg)
xml = etree.tostring(xml, pretty_print=True, encoding="unicode")
except Exception:
xml = bytes2str(arg).replace('><', '>\n<').replace('><', '>\n<')
return xml.replace(' ', ' ').replace('\t', ' ')
def pformat(arg, maxlines=None, linewidth=None, compact=True):
"""Return pretty formatted representation of object as string."""
if maxlines is None:
maxlines = TIFF.PRINT_MAX_LINES
elif not maxlines:
maxlines = 2**32
if linewidth is None:
linewidth = TIFF.PRINT_LINE_WIDTH
elif not linewidth:
linewidth = 2**32
numpy.set_printoptions(threshold=100, linewidth=linewidth)
if isinstance(arg, basestring):
if arg[:5].lower() in ('<?xml', b'<?xml'):
arg = pformat_xml(arg)
elif isinstance(arg, bytes):
try:
arg = bytes2str(arg)
arg = arg.replace('\r', '\n').replace('\n\n', '\n')
except Exception:
import binascii # delayed import
import pprint # delayed import
arg = binascii.hexlify(arg)
arg = pprint.pformat(arg, width=linewidth)
maxlines = min(maxlines, 16)
arg = arg.rstrip()
elif isinstance(arg, numpy.record):
arg = arg.pprint()
else:
from pprint import pformat # delayed import
compact = {} if sys.version_info[0] == 2 else dict(compact=compact)
arg = pformat(arg, width=linewidth, **compact)
argl = list(arg.splitlines())
if len(argl) > maxlines:
arg = '\n'.join(argl[:maxlines] +
['...truncated to %i lines.' % maxlines])
return arg
def snipstr(string, length=16, ellipse=None):
"""Return string cut in middle to specified length.
>>> snipstr('abcdefghijklmnop', 8)
'abcd…nop'
"""
size = len(string)
if size <= length:
return string
if ellipse is None:
if isinstance(string, bytes):
ellipse = b'...'
else:
ellipse = u'\u2026'
esize = len(ellipse)
if length < esize + 1:
return string[:length]
if length < esize + 4:
return string[:length-esize] + ellipse
half = (length - esize) // 2
return string[:half + (length-esize) % 2] + ellipse + string[-half:]
def enumarg(enum, arg):
"""Return enum member from its name or value.
>>> enumarg(TIFF.PHOTOMETRIC, 2)
<PHOTOMETRIC.RGB: 2>
>>> enumarg(TIFF.PHOTOMETRIC, 'RGB')
<PHOTOMETRIC.RGB: 2>
"""
try:
return enum(arg)
except Exception:
try:
return enum[arg.upper()]
except Exception:
raise ValueError("invalid argument %s" % arg)
def parse_kwargs(kwargs, *keys, **keyvalues):
"""Return dict with keys from keys|keyvals and values from kwargs|keyvals.
Existing keys are deleted from kwargs.
>>> kwargs = {'one': 1, 'two': 2, 'four': 4}
>>> kwargs2 = parse_kwargs(kwargs, 'two', 'three', four=None, five=5)
>>> kwargs == {'one': 1}
True
>>> kwargs2 == {'two': 2, 'four': 4, 'five': 5}
True
"""
result = {}
for key in keys:
if key in kwargs:
result[key] = kwargs[key]
del kwargs[key]
for key, value in keyvalues.items():
if key in kwargs:
result[key] = kwargs[key]
del kwargs[key]
else:
result[key] = value
return result
def update_kwargs(kwargs, **keyvalues):
"""Update dict with keys and values if keys do not already exist.
>>> kwargs = {'one': 1, }
>>> update_kwargs(kwargs, one=None, two=2)
>>> kwargs == {'one': 1, 'two': 2}
True
"""
for key, value in keyvalues.items():
if key not in kwargs:
kwargs[key] = value
def lsm2bin(lsmfile, binfile=None, tile=(256, 256), verbose=True):
"""Convert [MP]TZCYX LSM file to series of BIN files.
One BIN file containing 'ZCYX' data is created for each position, time,
and tile. The position, time, and tile indices are encoded at the end
of the filenames.
"""
verbose = print_ if verbose else nullfunc
if binfile is None:
binfile = lsmfile
elif binfile.lower() == 'none':
binfile = None
if binfile:
binfile += "_(z%ic%iy%ix%i)_m%%ip%%it%%03iy%%ix%%i.bin"
verbose("\nOpening LSM file... ", end='', flush=True)
start_time = time.time()
with TiffFile(lsmfile) as lsm:
if not lsm.is_lsm:
verbose("\n", lsm, flush=True)
raise ValueError("not a LSM file")
series = lsm.series[0] # first series contains the image data
shape = series.shape
axes = series.axes
dtype = series.dtype
size = product(shape) * dtype.itemsize
verbose("%.3f s" % (time.time() - start_time))
# verbose(lsm, flush=True)
verbose("Image\n axes: %s\n shape: %s\n dtype: %s\n size: %s"
% (axes, shape, dtype, format_size(size)), flush=True)
if not series.axes.endswith('TZCYX'):
raise ValueError("not a *TZCYX LSM file")
verbose("Copying image from LSM to BIN files", end='', flush=True)
start_time = time.time()
tiles = shape[-2] // tile[-2], shape[-1] // tile[-1]
if binfile:
binfile = binfile % (shape[-4], shape[-3], tile[0], tile[1])
shape = (1,) * (7-len(shape)) + shape
# cache for ZCYX stacks and output files
data = numpy.empty(shape[3:], dtype=dtype)
out = numpy.empty((shape[-4], shape[-3], tile[0], tile[1]),
dtype=dtype)
# iterate over Tiff pages containing data
pages = iter(series.pages)
for m in range(shape[0]): # mosaic axis
for p in range(shape[1]): # position axis
for t in range(shape[2]): # time axis
for z in range(shape[3]): # z slices
data[z] = next(pages).asarray()
for y in range(tiles[0]): # tile y
for x in range(tiles[1]): # tile x
out[:] = data[...,
y*tile[0]:(y+1)*tile[0],
x*tile[1]:(x+1)*tile[1]]
if binfile:
out.tofile(binfile % (m, p, t, y, x))
verbose('.', end='', flush=True)
verbose(" %.3f s" % (time.time() - start_time))
def imshow(data, title=None, vmin=0, vmax=None, cmap=None,
bitspersample=None, photometric='RGB',
interpolation=None, dpi=96, figure=None, subplot=111, maxdim=32768,
**kwargs):
"""Plot n-dimensional images using matplotlib.pyplot.
Return figure, subplot and plot axis.
Requires pyplot already imported C{from matplotlib import pyplot}.
Parameters
----------
bitspersample : int or None
Number of bits per channel in integer RGB images.
photometric : {'MINISWHITE', 'MINISBLACK', 'RGB', or 'PALETTE'}
The color space of the image data.
title : str
Window and subplot title.
figure : matplotlib.figure.Figure (optional).
Matplotlib to use for plotting.
subplot : int
A matplotlib.pyplot.subplot axis.
maxdim : int
maximum image width and length.
kwargs : optional
Arguments for matplotlib.pyplot.imshow.
"""
isrgb = photometric in ('RGB',) # 'PALETTE'
if isrgb and not (data.shape[-1] in (3, 4) or (
data.ndim > 2 and data.shape[-3] in (3, 4))):
isrgb = False
photometric = 'MINISWHITE'
data = data.squeeze()
if photometric in ('MINISWHITE', 'MINISBLACK', None):
data = reshape_nd(data, 2)
else:
data = reshape_nd(data, 3)
dims = data.ndim
if dims < 2:
raise ValueError("not an image")
elif dims == 2:
dims = 0
isrgb = False
else:
if isrgb and data.shape[-3] in (3, 4):
data = numpy.swapaxes(data, -3, -2)
data = numpy.swapaxes(data, -2, -1)
elif not isrgb and (data.shape[-1] < data.shape[-2] // 8 and
data.shape[-1] < data.shape[-3] // 8 and
data.shape[-1] < 5):
data = numpy.swapaxes(data, -3, -1)
data = numpy.swapaxes(data, -2, -1)
isrgb = isrgb and data.shape[-1] in (3, 4)
dims -= 3 if isrgb else 2
if isrgb:
data = data[..., :maxdim, :maxdim, :maxdim]
else:
data = data[..., :maxdim, :maxdim]
if photometric == 'PALETTE' and isrgb:
datamax = data.max()
if datamax > 255:
data = data >> 8 # possible precision loss
data = data.astype('B')
elif data.dtype.kind in 'ui':
if not (isrgb and data.dtype.itemsize <= 1) or bitspersample is None:
try:
bitspersample = int(math.ceil(math.log(data.max(), 2)))
except Exception:
bitspersample = data.dtype.itemsize * 8
elif not isinstance(bitspersample, inttypes):
# bitspersample can be tuple, e.g. (5, 6, 5)
bitspersample = data.dtype.itemsize * 8
datamax = 2**bitspersample
if isrgb:
if bitspersample < 8:
data = data << (8 - bitspersample)
elif bitspersample > 8:
data = data >> (bitspersample - 8) # precision loss
data = data.astype('B')
elif data.dtype.kind == 'f':
datamax = data.max()
if isrgb and datamax > 1.0:
if data.dtype.char == 'd':
data = data.astype('f')
data /= datamax
else:
data = data / datamax
elif data.dtype.kind == 'b':
datamax = 1
elif data.dtype.kind == 'c':
data = numpy.absolute(data)
datamax = data.max()
if not isrgb:
if vmax is None:
vmax = datamax
if vmin is None:
if data.dtype.kind == 'i':
dtmin = numpy.iinfo(data.dtype).min
vmin = numpy.min(data)
if vmin == dtmin:
vmin = numpy.min(data > dtmin)
if data.dtype.kind == 'f':
dtmin = numpy.finfo(data.dtype).min
vmin = numpy.min(data)
if vmin == dtmin:
vmin = numpy.min(data > dtmin)
else:
vmin = 0
pyplot = sys.modules['matplotlib.pyplot']
if figure is None:
pyplot.rc('font', family='sans-serif', weight='normal', size=8)
figure = pyplot.figure(dpi=dpi, figsize=(10.3, 6.3), frameon=True,
facecolor='1.0', edgecolor='w')
try:
figure.canvas.manager.window.title(title)
except Exception:
pass
l = len(title.splitlines()) if title else 1
pyplot.subplots_adjust(bottom=0.03*(dims+2), top=0.98-l*0.03,
left=0.1, right=0.95, hspace=0.05, wspace=0.0)
subplot = pyplot.subplot(subplot)
if title:
try:
title = unicode(title, 'Windows-1252')
except TypeError:
pass
pyplot.title(title, size=11)
if cmap is None:
if data.dtype.kind in 'ubf' or vmin == 0:
cmap = 'viridis'
else:
cmap = 'coolwarm'
if photometric == 'MINISWHITE':
cmap += '_r'
image = pyplot.imshow(data[(0,) * dims].squeeze(), vmin=vmin, vmax=vmax,
cmap=cmap, interpolation=interpolation, **kwargs)
if not isrgb:
pyplot.colorbar() # panchor=(0.55, 0.5), fraction=0.05
def format_coord(x, y):
# callback function to format coordinate display in toolbar
x = int(x + 0.5)
y = int(y + 0.5)
try:
if dims:
return "%s @ %s [%4i, %4i]" % (
curaxdat[1][y, x], current, y, x)
return "%s @ [%4i, %4i]" % (data[y, x], y, x)
except IndexError:
return ''
def none(event):
return ''
subplot.format_coord = format_coord
image.get_cursor_data = none
image.format_cursor_data = none
if dims:
current = list((0,) * dims)
curaxdat = [0, data[tuple(current)].squeeze()]
sliders = [pyplot.Slider(
pyplot.axes([0.125, 0.03*(axis+1), 0.725, 0.025]),
'Dimension %i' % axis, 0, data.shape[axis]-1, 0, facecolor='0.5',
valfmt='%%.0f [%i]' % data.shape[axis]) for axis in range(dims)]
for slider in sliders:
slider.drawon = False
def set_image(current, sliders=sliders, data=data):
# change image and redraw canvas
curaxdat[1] = data[tuple(current)].squeeze()
image.set_data(curaxdat[1])
for ctrl, index in zip(sliders, current):
ctrl.eventson = False
ctrl.set_val(index)
ctrl.eventson = True
figure.canvas.draw()
def on_changed(index, axis, data=data, current=current):
# callback function for slider change event
index = int(round(index))
curaxdat[0] = axis
if index == current[axis]:
return
if index >= data.shape[axis]:
index = 0
elif index < 0:
index = data.shape[axis] - 1
current[axis] = index
set_image(current)
def on_keypressed(event, data=data, current=current):
# callback function for key press event
key = event.key
axis = curaxdat[0]
if str(key) in '0123456789':
on_changed(key, axis)
elif key == 'right':
on_changed(current[axis] + 1, axis)
elif key == 'left':
on_changed(current[axis] - 1, axis)
elif key == 'up':
curaxdat[0] = 0 if axis == len(data.shape)-1 else axis + 1
elif key == 'down':
curaxdat[0] = len(data.shape)-1 if axis == 0 else axis - 1
elif key == 'end':
on_changed(data.shape[axis] - 1, axis)
elif key == 'home':
on_changed(0, axis)
figure.canvas.mpl_connect('key_press_event', on_keypressed)
for axis, ctrl in enumerate(sliders):
ctrl.on_changed(lambda k, a=axis: on_changed(k, a))
return figure, subplot, image
def _app_show():
"""Block the GUI. For use as skimage plugin."""
pyplot = sys.modules['matplotlib.pyplot']
pyplot.show()
def askopenfilename(**kwargs):
"""Return file name(s) from Tkinter's file open dialog."""
try:
from Tkinter import Tk
import tkFileDialog as filedialog
except ImportError:
from tkinter import Tk, filedialog
root = Tk()
root.withdraw()
root.update()
filenames = filedialog.askopenfilename(**kwargs)
root.destroy()
return filenames
def main(argv=None):
"""Command line usage main function."""
if float(sys.version[0:3]) < 2.7:
print("This script requires Python version 2.7 or better.")
print("This is Python version %s" % sys.version)
return 0
if argv is None:
argv = sys.argv
import optparse # TODO: use argparse
parser = optparse.OptionParser(
usage="usage: %prog [options] path",
description="Display image data in TIFF files.",
version="%%prog %s" % __version__)
opt = parser.add_option
opt('-p', '--page', dest='page', type='int', default=-1,
help="display single page")
opt('-s', '--series', dest='series', type='int', default=-1,
help="display series of pages of same shape")
opt('--nomultifile', dest='nomultifile', action='store_true',
default=False, help="do not read OME series from multiple files")
opt('--noplots', dest='noplots', type='int', default=8,
help="maximum number of plots")
opt('--interpol', dest='interpol', metavar='INTERPOL', default='bilinear',
help="image interpolation method")
opt('--dpi', dest='dpi', type='int', default=96,
help="plot resolution")
opt('--vmin', dest='vmin', type='int', default=None,
help="minimum value for colormapping")
opt('--vmax', dest='vmax', type='int', default=None,
help="maximum value for colormapping")
opt('--debug', dest='debug', action='store_true', default=False,
help="raise exception on failures")
opt('--doctest', dest='doctest', action='store_true', default=False,
help="runs the docstring examples")
opt('-v', '--detail', dest='detail', type='int', default=2)
opt('-q', '--quiet', dest='quiet', action='store_true')
settings, path = parser.parse_args()
path = ' '.join(path)
if settings.doctest:
import doctest
doctest.testmod(optionflags=doctest.ELLIPSIS)
return 0
if not path:
path = askopenfilename(title="Select a TIFF file",
filetypes=TIFF.FILEOPEN_FILTER)
if not path:
parser.error("No file specified")
if any(i in path for i in '?*'):
path = glob.glob(path)
if not path:
print('no files match the pattern')
return 0
# TODO: handle image sequences
path = path[0]
if not settings.quiet:
print("\nReading file structure...", end=' ')
start = time.time()
try:
tif = TiffFile(path, multifile=not settings.nomultifile)
except Exception as e:
if settings.debug:
raise
else:
print("\n", e)
sys.exit(0)
if not settings.quiet:
print("%.3f ms" % ((time.time()-start) * 1e3))
if tif.is_ome:
settings.norgb = True
images = []
if settings.noplots > 0:
if not settings.quiet:
print("Reading image data... ", end=' ')
def notnone(x):
return next(i for i in x if i is not None)
start = time.time()
try:
if settings.page >= 0:
images = [(tif.asarray(key=settings.page),
tif[settings.page], None)]
elif settings.series >= 0:
images = [(tif.asarray(series=settings.series),
notnone(tif.series[settings.series].pages),
tif.series[settings.series])]
else:
images = []
for i, s in enumerate(tif.series[:settings.noplots]):
try:
images.append((tif.asarray(series=i),
notnone(s.pages),
tif.series[i]))
except ValueError as e:
images.append((None, notnone(s.pages), None))
if settings.debug:
raise
else:
print("\nSeries %i failed: %s... " % (i, e),
end='')
if not settings.quiet:
print("%.3f ms" % ((time.time()-start) * 1e3))
except Exception as e:
if settings.debug:
raise
else:
print(e)
if not settings.quiet:
print()
print(TiffFile.__str__(tif, detail=int(settings.detail)))
print()
tif.close()
if images and settings.noplots > 0:
try:
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot
except ImportError as e:
warnings.warn("failed to import matplotlib.\n%s" % e)
else:
for img, page, series in images:
if img is None:
continue
vmin, vmax = settings.vmin, settings.vmax
if 'GDAL_NODATA' in page.tags:
try:
vmin = numpy.min(
img[img > float(page.tags['GDAL_NODATA'].value)])
except ValueError:
pass
if tif.is_stk:
try:
vmin = tif.stk_metadata['MinScale']
vmax = tif.stk_metadata['MaxScale']
except KeyError:
pass
else:
if vmax <= vmin:
vmin, vmax = settings.vmin, settings.vmax
if series:
title = "%s\n%s\n%s" % (str(tif), str(page), str(series))
else:
title = "%s\n %s" % (str(tif), str(page))
photometric = 'MINISBLACK'
if page.photometric not in (3,):
photometric = TIFF.PHOTOMETRIC(page.photometric).name
imshow(img, title=title, vmin=vmin, vmax=vmax,
bitspersample=page.bitspersample,
photometric=photometric,
interpolation=settings.interpol,
dpi=settings.dpi)
pyplot.show()
if sys.version_info[0] == 2:
inttypes = int, long # noqa
def print_(*args, **kwargs):
"""Print function with flush support."""
flush = kwargs.pop('flush', False)
print(*args, **kwargs)
if flush:
sys.stdout.flush()
def bytes2str(b, encoding=None, errors=None):
"""Return string from bytes."""
return b
def str2bytes(s, encoding=None):
"""Return bytes from string."""
return s
def byte2int(b):
"""Return value of byte as int."""
return ord(b)
class FileNotFoundError(IOError):
pass
TiffFrame = TiffPage # noqa
else:
inttypes = int
basestring = str, bytes
unicode = str
print_ = print
def bytes2str(b, encoding=None, errors='strict'):
"""Return unicode string from encoded bytes."""
if encoding is not None:
return b.decode(encoding, errors)
try:
return b.decode('utf-8', errors)
except UnicodeDecodeError:
return b.decode('cp1252', errors)
def str2bytes(s, encoding='cp1252'):
"""Return bytes from unicode string."""
return s.encode(encoding)
def byte2int(b):
"""Return value of byte as int."""
return b
if __name__ == "__main__":
sys.exit(main())
|