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
|
package ij;
import java.awt.*;
import java.awt.image.*;
import java.net.URL;
import java.util.*;
import ij.process.*;
import ij.io.*;
import ij.gui.*;
import ij.measure.*;
import ij.plugin.filter.Analyzer;
import ij.util.Tools;
import ij.macro.Interpreter;
import ij.plugin.frame.ContrastAdjuster;
import ij.plugin.frame.Recorder;
import ij.plugin.Converter;
import ij.plugin.Duplicator;
import ij.plugin.RectToolOptions;
/**
An ImagePlus contain an ImageProcessor (2D image) or an ImageStack (3D, 4D or 5D image).
It also includes metadata (spatial calibration and possibly the directory/file where
it was read from). The ImageProcessor contains the pixel data (8-bit, 16-bit, float or RGB)
of the 2D image and some basic methods to manipulate it. An ImageStack is essentually
a list ImageProcessors of same type and size.
@see ij.process.ImageProcessor
@see ij.ImageStack
@see ij.gui.ImageWindow
@see ij.gui.ImageCanvas
*/
public class ImagePlus implements ImageObserver, Measurements, Cloneable {
/** 8-bit grayscale (unsigned)*/
public static final int GRAY8 = 0;
/** 16-bit grayscale (unsigned) */
public static final int GRAY16 = 1;
/** 32-bit floating-point grayscale */
public static final int GRAY32 = 2;
/** 8-bit indexed color */
public static final int COLOR_256 = 3;
/** 32-bit RGB color */
public static final int COLOR_RGB = 4;
/** True if any changes have been made to this image. */
public boolean changes;
protected Image img;
protected ImageProcessor ip;
protected ImageWindow win;
protected Roi roi;
protected int currentSlice;
protected static final int OPENED=0, CLOSED=1, UPDATED=2;
protected boolean compositeImage;
protected int width;
protected int height;
protected boolean locked = false;
protected int nChannels = 1;
protected int nSlices = 1;
protected int nFrames = 1;
private ImageJ ij = IJ.getInstance();
private String title;
private String url;
private FileInfo fileInfo;
private int imageType = GRAY8;
private ImageStack stack;
private static int currentID = -1;
private int ID;
private static Component comp;
private boolean imageLoaded;
private int imageUpdateY, imageUpdateW;
private Properties properties;
private long startTime;
private Calibration calibration;
private static Calibration globalCalibration;
private boolean activated;
private boolean ignoreFlush;
private boolean errorLoadingImage;
private static ImagePlus clipboard;
private static Vector listeners = new Vector();
private boolean openAsHyperStack;
private int[] position = {1,1,1};
private boolean noUpdateMode;
private ImageCanvas flatteningCanvas;
private Overlay overlay;
private boolean hideOverlay;
private static int default16bitDisplayRange;
/** Constructs an uninitialized ImagePlus. */
public ImagePlus() {
ID = --currentID;
title="null";
}
/** Constructs an ImagePlus from an Image or BufferedImage. The first
argument will be used as the title of the window that displays the image.
Throws an IllegalStateException if an error occurs while loading the image. */
public ImagePlus(String title, Image img) {
this.title = title;
ID = --currentID;
if (img!=null)
setImage(img);
}
/** Constructs an ImagePlus from an ImageProcessor. */
public ImagePlus(String title, ImageProcessor ip) {
setProcessor(title, ip);
ID = --currentID;
}
/** Constructs an ImagePlus from a TIFF, BMP, DICOM, FITS,
PGM, GIF or JPRG specified by a path or from a TIFF, DICOM,
GIF or JPEG specified by a URL. */
public ImagePlus(String pathOrURL) {
Opener opener = new Opener();
ImagePlus imp = null;
boolean isURL = pathOrURL.indexOf("://")>0;
if (isURL)
imp = opener.openURL(pathOrURL);
else
imp = opener.openImage(pathOrURL);
if (imp!=null) {
if (imp.getStackSize()>1)
setStack(imp.getTitle(), imp.getStack());
else
setProcessor(imp.getTitle(), imp.getProcessor());
setCalibration(imp.getCalibration());
properties = imp.getProperties();
setFileInfo(imp.getOriginalFileInfo());
setDimensions(imp.getNChannels(), imp.getNSlices(), imp.getNFrames());
if (isURL)
this.url = pathOrURL;
ID = --currentID;
}
}
/** Constructs an ImagePlus from a stack. */
public ImagePlus(String title, ImageStack stack) {
setStack(title, stack);
ID = --currentID;
}
/** Locks the image so other threads can test to see if it
is in use. Returns true if the image was successfully locked.
Beeps, displays a message in the status bar, and returns
false if the image is already locked. */
public synchronized boolean lock() {
if (locked) {
IJ.beep();
IJ.showStatus("\"" + title + "\" is locked");
//if (IJ.macroRunning()) {
// IJ.error("Image is locked");
// Macro.abort();
//}
return false;
} else {
locked = true;
if (IJ.debugMode) IJ.log(title + ": lock");
return true;
}
}
/** Similar to lock, but doesn't beep and display an error
message if the attempt to lock the image fails. */
public synchronized boolean lockSilently() {
if (locked)
return false;
else {
locked = true;
if (IJ.debugMode) IJ.log(title + ": lock silently");
return true;
}
}
/** Unlocks the image. */
public synchronized void unlock() {
locked = false;
if (IJ.debugMode) IJ.log(title + ": unlock");
}
private void waitForImage(Image img) {
if (comp==null) {
comp = IJ.getInstance();
if (comp==null)
comp = new Canvas();
}
imageLoaded = false;
if (!comp.prepareImage(img, this)) {
double progress;
waitStart = System.currentTimeMillis();
while (!imageLoaded && !errorLoadingImage) {
//IJ.showStatus(imageUpdateY+" "+imageUpdateW);
IJ.wait(30);
if (imageUpdateW>1) {
progress = (double)imageUpdateY/imageUpdateW;
if (!(progress<1.0)) {
progress = 1.0 - (progress-1.0);
if (progress<0.0) progress = 0.9;
}
showProgress(progress);
}
}
showProgress(1.0);
}
}
long waitStart;
private void showProgress(double percent) {
if ((System.currentTimeMillis()-waitStart)>500L)
IJ.showProgress(percent);
}
/** Draws the image. If there is an ROI, its
outline is also displayed. Does nothing if there
is no window associated with this image (i.e. show()
has not been called).*/
public void draw(){
if (win!=null)
win.getCanvas().repaint();
}
/** Draws image and roi outline using a clip rect. */
public void draw(int x, int y, int width, int height){
if (win!=null) {
ImageCanvas ic = win.getCanvas();
double mag = ic.getMagnification();
x = ic.screenX(x);
y = ic.screenY(y);
width = (int)(width*mag);
height = (int)(height*mag);
ic.repaint(x, y, width, height);
if (listeners.size()>0 && roi!=null && roi.getPasteMode()!=Roi.NOT_PASTING)
notifyListeners(UPDATED);
}
}
/** Updates this image from the pixel data in its
associated ImageProcessor, then displays it. Does
nothing if there is no window associated with
this image (i.e. show() has not been called).*/
public void updateAndDraw() {
if (ip!=null) {
if (win!=null) {
win.getCanvas().setImageUpdated();
if (listeners.size()>0) notifyListeners(UPDATED);
}
draw();
}
}
/** Updates this image from the pixel data in its
associated ImageProcessor, then displays it.
The CompositeImage class overrides this method
to only update the current channel. */
public void updateChannelAndDraw() {
updateAndDraw();
}
/** Returns a reference to the current ImageProcessor. The
CompositeImage class overrides this method so it returns
the processor associated with the current channel. */
public ImageProcessor getChannelProcessor() {
return getProcessor();
}
/* The CompositeImage class overrides this method to
return, as an array, copies of this image's channel LUTs. */
public LUT[] getLuts() {
return null;
//ImageProcessor ip = getProcessor();
//ColorModel cm = ip.getColorModel();
//if (cm instanceof IndexColorModel) {
// LUT[] luts = new LUT[1];
// luts[0] = new LUT((IndexColorModel)cm, ip.getMin(), ip.getMax());
// return luts;
//} else
// return null;
}
/** Calls draw to draw the image and also repaints the
image window to force the information displayed above
the image (dimension, type, size) to be updated. */
public void repaintWindow() {
if (win!=null) {
draw();
win.repaint();
}
}
/** Calls updateAndDraw to update from the pixel data
and draw the image, and also repaints the image
window to force the information displayed above
the image (dimension, type, size) to be updated. */
public void updateAndRepaintWindow() {
if (win!=null) {
updateAndDraw();
win.repaint();
}
}
/** ImageCanvas.paint() calls this method when the
ImageProcessor has generated new image. */
public void updateImage() {
if (ip!=null)
img = ip.createImage();
}
/** Closes the window, if any, that is displaying this image. */
public void hide() {
if (win==null) {
Interpreter.removeBatchModeImage(this);
return;
}
boolean unlocked = lockSilently();
changes = false;
win.close();
win = null;
if (unlocked) unlock();
}
/** Closes this image and sets the ImageProcessor to null. To avoid the
"Save changes?" dialog, first set the public 'changes' variable to false. */
public void close() {
ImageWindow win = getWindow();
if (win!=null) {
//if (IJ.isWindows() && IJ.isJava14())
// changes = false; // avoid 'save changes?' dialog and potential Java 1.5 deadlocks
win.close();
} else {
if (WindowManager.getCurrentImage()==this)
WindowManager.setTempCurrentImage(null);
killRoi(); //save any ROI so it can be restored later
Interpreter.removeBatchModeImage(this);
}
}
/** Opens a window to display this image and clears the status bar. */
public void show() {
show("");
}
/** Opens a window to display this image and displays
'statusMessage' in the status bar. */
public void show(String statusMessage) {
if (win!=null) return;
if ((IJ.isMacro() && ij==null) || Interpreter.isBatchMode()) {
if (isComposite()) ((CompositeImage)this).reset();
ImagePlus img = WindowManager.getCurrentImage();
if (img!=null) img.saveRoi();
WindowManager.setTempCurrentImage(this);
Interpreter.addBatchModeImage(this);
return;
}
if (Prefs.useInvertingLut && getBitDepth()==8 && ip!=null && !ip.isInvertedLut()&& !ip.isColorLut())
invertLookupTable();
img = getImage();
if ((img!=null) && (width>=0) && (height>=0)) {
activated = false;
int stackSize = getStackSize();
//if (compositeImage) stackSize /= nChannels;
if (stackSize>1)
win = new StackWindow(this);
else
win = new ImageWindow(this);
if (roi!=null) roi.setImage(this);
if (overlay!=null && getCanvas()!=null)
getCanvas().setOverlay(overlay);
draw();
IJ.showStatus(statusMessage);
if (IJ.isMacro()) { // wait for window to be activated
long start = System.currentTimeMillis();
while (!activated) {
IJ.wait(5);
if ((System.currentTimeMillis()-start)>2000) {
WindowManager.setTempCurrentImage(this);
break; // 2 second timeout
}
}
}
if (imageType==GRAY16 && default16bitDisplayRange!=0) {
resetDisplayRange();
updateAndDraw();
}
if (stackSize>1) {
int c = getChannel();
int z = getSlice();
int t = getFrame();
if (c>1 || z>1 || t>1)
setPosition(c, z, t);
}
notifyListeners(OPENED);
}
}
void invertLookupTable() {
int nImages = getStackSize();
ip.invertLut();
if (nImages==1)
ip.invert();
else {
ImageStack stack2 = getStack();
for (int i=1; i<=nImages; i++)
stack2.getProcessor(i).invert();
stack2.setColorModel(ip.getColorModel());
}
}
/** Called by ImageWindow.windowActivated(). */
public void setActivated() {
activated = true;
}
/** Returns this image as a AWT image. */
public Image getImage() {
if (img==null && ip!=null)
img = ip.createImage();
return img;
}
/** Returns this image as a BufferedImage. */
public BufferedImage getBufferedImage() {
if (isComposite())
return (new ColorProcessor(getImage())).getBufferedImage();
else
return ip.getBufferedImage();
}
/** Returns this image's unique numeric ID. */
public int getID() {
return ID;
}
/** Replaces the image, if any, with the one specified.
Throws an IllegalStateException if an error occurs
while loading the image. */
public void setImage(Image img) {
if (img instanceof BufferedImage) {
BufferedImage bi = (BufferedImage)img;
if (bi.getType()==BufferedImage.TYPE_USHORT_GRAY) {
setProcessor(null, new ShortProcessor(bi));
return;
} else if (bi.getType()==BufferedImage.TYPE_BYTE_GRAY) {
setProcessor(null, new ByteProcessor(bi));
return;
}
}
roi = null;
errorLoadingImage = false;
waitForImage(img);
if (errorLoadingImage)
throw new IllegalStateException ("Error loading image");
this.img = img;
int newWidth = img.getWidth(ij);
int newHeight = img.getHeight(ij);
boolean dimensionsChanged = newWidth!=width || newHeight!=height;
width = newWidth;
height = newHeight;
ip = null;
stack = null;
LookUpTable lut = new LookUpTable(img);
int type;
if (lut.getMapSize() > 0) {
if (lut.isGrayscale())
type = GRAY8;
else
type = COLOR_256;
} else
type = COLOR_RGB;
setType(type);
setupProcessor();
this.img = ip.createImage();
if (win!=null) {
if (dimensionsChanged)
win = new ImageWindow(this);
else
repaintWindow();
}
}
/** Replaces this image with the specified ImagePlus. May
not work as expected if 'imp' is a CompositeImage
and this image is not. */
public void setImage(ImagePlus imp) {
if (imp.getWindow()!=null)
imp = imp.duplicate();
ImageStack stack2 = imp.getStack();
if (imp.isHyperStack())
setOpenAsHyperStack(true);
setStack(stack2, imp.getNChannels(), imp.getNSlices(), imp.getNFrames());
}
/** Replaces the ImageProcessor with the one specified and updates the display. */
public void setProcessor(ImageProcessor ip) {
setProcessor(null, ip);
}
/** Replaces the ImageProcessor with the one specified and updates the display.
Set 'title' to null to leave the image title unchanged. */
public void setProcessor(String title, ImageProcessor ip) {
if (ip==null || ip.getPixels()==null)
throw new IllegalArgumentException("ip null or ip.getPixels() null");
int stackSize = getStackSize();
if (stackSize>1 && (ip.getWidth()!=width || ip.getHeight()!=height))
throw new IllegalArgumentException("ip wrong size");
if (stackSize<=1) {
stack = null;
setCurrentSlice(1);
}
setProcessor2(title, ip, null);
}
void setProcessor2(String title, ImageProcessor ip, ImageStack newStack) {
if (title!=null) setTitle(title);
this.ip = ip;
if (ij!=null) ip.setProgressBar(ij.getProgressBar());
int stackSize = 1;
if (stack!=null) {
stackSize = stack.getSize();
if (currentSlice>stackSize) setCurrentSlice(stackSize);
}
img = null;
boolean dimensionsChanged = width>0 && height>0 && (width!=ip.getWidth() || height!=ip.getHeight());
if (dimensionsChanged) roi = null;
int type;
if (ip instanceof ByteProcessor)
type = GRAY8;
else if (ip instanceof ColorProcessor)
type = COLOR_RGB;
else if (ip instanceof ShortProcessor)
type = GRAY16;
else
type = GRAY32;
if (width==0)
imageType = type;
else
setType(type);
width = ip.getWidth();
height = ip.getHeight();
if (win!=null) {
if (dimensionsChanged && stackSize==1)
win.updateImage(this);
else if (newStack==null)
repaintWindow();
draw();
}
}
/** Replaces the image with the specified stack and updates the display. */
public void setStack(ImageStack stack) {
setStack(null, stack);
}
/** Replaces the image with the specified stack and updates
the display. Set 'title' to null to leave the title unchanged. */
public void setStack(String title, ImageStack newStack) {
int newStackSize = newStack.getSize();
if (newStackSize==0)
throw new IllegalArgumentException("Stack is empty");
if (!newStack.isVirtual()) {
Object[] arrays = newStack.getImageArray();
if (arrays==null || (arrays.length>0&&arrays[0]==null))
throw new IllegalArgumentException("Stack pixel array null");
}
boolean sliderChange = false;
if (win!=null && (win instanceof StackWindow)) {
int nScrollbars = ((StackWindow)win).getNScrollbars();
if (nScrollbars>0 && newStackSize==1)
sliderChange = true;
else if (nScrollbars==0 && newStackSize>1)
sliderChange = true;
}
if (currentSlice<1) setCurrentSlice(1);
boolean resetCurrentSlice = currentSlice>newStackSize;
if (resetCurrentSlice) setCurrentSlice(newStackSize);
ImageProcessor ip = newStack.getProcessor(currentSlice);
boolean dimensionsChanged = width>0 && height>0 && (width!=ip.getWidth()||height!=ip.getHeight());
this.stack = newStack;
setProcessor2(title, ip, newStack);
if (win==null) {
if (resetCurrentSlice) setSlice(currentSlice);
return;
}
boolean invalidDimensions = isDisplayedHyperStack() && !((StackWindow)win).validDimensions();
if (newStackSize>1 && !(win instanceof StackWindow)) {
if (isDisplayedHyperStack()) setOpenAsHyperStack(true);
win = new StackWindow(this, getCanvas()); // replaces this window
setPosition(1, 1, 1);
} else if (newStackSize>1 && invalidDimensions) {
if (isDisplayedHyperStack()) setOpenAsHyperStack(true);
win = new StackWindow(this); // replaces this window
setPosition(1, 1, 1);
} else if (dimensionsChanged || sliderChange)
win.updateImage(this);
else
repaintWindow();
if (resetCurrentSlice) setSlice(currentSlice);
}
public void setStack(ImageStack stack, int nChannels, int nSlices, int nFrames) {
if (nChannels*nSlices*nFrames!=stack.getSize())
throw new IllegalArgumentException("channels*slices*frames!=stackSize");
this.nChannels = nChannels;
this.nSlices = nSlices;
this.nFrames = nFrames;
if (isComposite())
((CompositeImage)this).setChannelsUpdated();
setStack(null, stack);
}
/** Saves this image's FileInfo so it can be later
retieved using getOriginalFileInfo(). */
public void setFileInfo(FileInfo fi) {
if (fi!=null)
fi.pixels = null;
fileInfo = fi;
}
/** Returns the ImageWindow that is being used to display
this image. Returns null if show() has not be called
or the ImageWindow has been closed. */
public ImageWindow getWindow() {
return win;
}
/** Returns true if this image is currently being displayed in a window. */
public boolean isVisible() {
return win!=null && win.isVisible();
}
/** This method should only be called from an ImageWindow. */
public void setWindow(ImageWindow win) {
this.win = win;
if (roi!=null)
roi.setImage(this); // update roi's 'ic' field
}
/** Returns the ImageCanvas being used to
display this image, or null. */
public ImageCanvas getCanvas() {
return win!=null?win.getCanvas():flatteningCanvas;
}
/** Sets current foreground color. */
public void setColor(Color c) {
if (ip!=null)
ip.setColor(c);
}
void setupProcessor() {
if (imageType==COLOR_RGB) {
if (ip == null || ip instanceof ByteProcessor)
ip = new ColorProcessor(getImage());
} else if (ip==null || (ip instanceof ColorProcessor))
ip = new ByteProcessor(getImage());
if (roi!=null && roi.isArea())
ip.setRoi(roi.getBounds());
else
ip.resetRoi();
}
public boolean isProcessor() {
return ip!=null;
}
/** Returns a reference to the current ImageProcessor. If there
is no ImageProcessor, it creates one. Returns null if this
ImagePlus contains no ImageProcessor and no AWT Image.
Sets the line width to the current line width and sets the
calibration table if the image is density calibrated. */
public ImageProcessor getProcessor() {
if (ip==null && img==null)
return null;
setupProcessor();
if (!compositeImage)
ip.setLineWidth(Line.getWidth());
if (ij!=null)
ip.setProgressBar(ij.getProgressBar());
Calibration cal = getCalibration();
if (cal.calibrated())
ip.setCalibrationTable(cal.getCTable());
else
ip.setCalibrationTable(null);
if (Recorder.record) {
Recorder recorder = Recorder.getInstance();
if (recorder!=null) recorder.imageUpdated(this);
}
return ip;
}
/** Frees RAM by setting the snapshot (undo) buffer in
the current ImageProcessor to null. */
public void trimProcessor() {
ImageProcessor ip2 = ip;
if (!locked && ip2!=null) {
if (IJ.debugMode) IJ.log(title + ": trimProcessor");
Roi roi2 = getRoi();
if (roi2!=null && roi2.getPasteMode()!=Roi.NOT_PASTING)
roi2.endPaste();
ip2.setSnapshotPixels(null);
}
}
/** For images with irregular ROIs, returns a byte mask, otherwise, returns
null. Mask pixels have a non-zero value. */
public ImageProcessor getMask() {
if (roi==null) {
if (ip!=null) ip.resetRoi();
return null;
}
ImageProcessor mask = roi.getMask();
if (mask==null)
return null;
if (ip!=null && roi!=null) {
ip.setMask(mask);
ip.setRoi(roi.getBounds());
}
return mask;
}
/** Returns an ImageStatistics object generated using the standard
measurement options (area, mean, mode, min and max).
This plugin demonstrates how get the area, mean and max of the
current image or selection:
<pre>
public class Get_Statistics implements PlugIn {
public void run(String arg) {
ImagePlus imp = IJ.getImage();
ImageStatistics stats = imp.getStatistics();
IJ.log("Area: "+stats.area);
IJ.log("Mean: "+stats.mean);
IJ.log("Max: "+stats.max);
}
}
</pre>
@see ij.process.ImageStatistics
@see ij.process.ImageStatistics#getStatistics
*/
public ImageStatistics getStatistics() {
return getStatistics(AREA+MEAN+MODE+MIN_MAX);
}
/** Returns an ImageStatistics object generated using the
specified measurement options. This plugin demonstrates how
get the area and centroid of the current selection:
<pre>
public class Get_Statistics implements PlugIn, Measurements {
public void run(String arg) {
ImagePlus imp = IJ.getImage();
ImageStatistics stats = imp.getStatistics(MEDIAN+CENTROID);
IJ.log("Median: "+stats.median);
IJ.log("xCentroid: "+stats.xCentroid);
IJ.log("yCentroid: "+stats.yCentroid);
}
}
</pre>
@see ij.process.ImageStatistics
@see ij.measure.Measurements
*/
public ImageStatistics getStatistics(int mOptions) {
return getStatistics(mOptions, 256, 0.0, 0.0);
}
/** Returns an ImageStatistics object generated using the
specified measurement options and histogram bin count.
Note: except for float images, the number of bins
is currently fixed at 256.
*/
public ImageStatistics getStatistics(int mOptions, int nBins) {
return getStatistics(mOptions, nBins, 0.0, 0.0);
}
/** Returns an ImageStatistics object generated using the
specified measurement options, histogram bin count and histogram range.
Note: for 8-bit and RGB images, the number of bins
is fixed at 256 and the histogram range is always 0-255.
*/
public ImageStatistics getStatistics(int mOptions, int nBins, double histMin, double histMax) {
setupProcessor();
if (roi!=null && roi.isArea())
ip.setRoi(roi);
else
ip.resetRoi();
ip.setHistogramSize(nBins);
Calibration cal = getCalibration();
if (getType()==GRAY16&& !(histMin==0.0&&histMax==0.0))
{histMin=cal.getRawValue(histMin); histMax=cal.getRawValue(histMax);}
ip.setHistogramRange(histMin, histMax);
ImageStatistics stats = ImageStatistics.getStatistics(ip, mOptions, cal);
ip.setHistogramSize(256);
ip.setHistogramRange(0.0, 0.0);
return stats;
}
/** Returns the image name. */
public String getTitle() {
if (title==null)
return "";
else
return title;
}
/** Returns a shortened version of image name that does not
include spaces or a file name extension. */
public String getShortTitle() {
String title = getTitle();
int index = title.indexOf(' ');
if (index>-1)
title = title.substring(0, index);
index = title.lastIndexOf('.');
if (index>0)
title = title.substring(0, index);
return title;
}
/** Sets the image name. */
public void setTitle(String title) {
if (title==null)
return;
if (win!=null) {
if (ij!=null)
Menus.updateWindowMenuItem(this.title, title);
String virtual = stack!=null && stack.isVirtual()?" (V)":"";
String global = getGlobalCalibration()!=null?" (G)":"";
String scale = "";
double magnification = win.getCanvas().getMagnification();
if (magnification!=1.0) {
double percent = magnification*100.0;
int digits = percent>100.0||percent==(int)percent?0:1;
scale = " (" + IJ.d2s(percent,digits) + "%)";
}
win.setTitle(title+virtual+global+scale);
}
this.title = title;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
/** If this is a stack, returns the number of slices, else returns 1. */
public int getStackSize() {
if (stack==null)
return 1;
else {
int slices = stack.getSize();
//if (compositeImage) slices /= nChannels;
if (slices<=0) slices = 1;
return slices;
}
}
/** If this is a stack, returns the actual number of images in the stack, else returns 1. */
public int getImageStackSize() {
if (stack==null)
return 1;
else {
int slices = stack.getSize();
if (slices==0) slices = 1;
return slices;
}
}
/** Sets the 3rd, 4th and 5th dimensions, where
<code>nChannels</code>*<code>nSlices</code>*<code>nFrames</code>
must be equal to the stack size. */
public void setDimensions(int nChannels, int nSlices, int nFrames) {
//IJ.log("setDimensions: "+nChannels+" "+nSlices+" "+nFrames+" "+getImageStackSize());
if (nChannels*nSlices*nFrames!=getImageStackSize() && ip!=null) {
//throw new IllegalArgumentException("channels*slices*frames!=stackSize");
nChannels = 1;
nSlices = getImageStackSize();
nFrames = 1;
if (isDisplayedHyperStack()) {
setOpenAsHyperStack(false);
new StackWindow(this);
setSlice(1);
}
}
boolean updateWin = isDisplayedHyperStack() && (this.nChannels!=nChannels||this.nSlices!=nSlices||this.nFrames!=nFrames);
this.nChannels = nChannels;
this.nSlices = nSlices;
this.nFrames = nFrames;
if (updateWin) {
if (nSlices!=getImageStackSize())
setOpenAsHyperStack(true);
ip=null; img=null;
setPositionWithoutUpdate(getChannel(), getSlice(), getFrame());
if (isComposite()) ((CompositeImage)this).reset();
new StackWindow(this);
setPosition(getChannel(), getSlice(), getFrame());
}
//IJ.log("setDimensions: "+ nChannels+" "+nSlices+" "+nFrames);
}
/** Returns 'true' if this image is a hyperstack. */
public boolean isHyperStack() {
return isDisplayedHyperStack() || (openAsHyperStack&&getNDimensions()>3);
}
/** Returns the number of dimensions (2, 3, 4 or 5). */
public int getNDimensions() {
int dimensions = 2;
int[] dim = getDimensions();
if (dim[2]>1) dimensions++;
if (dim[3]>1) dimensions++;
if (dim[4]>1) dimensions++;
return dimensions;
}
/** Returns 'true' if this is a hyperstack currently being displayed in a StackWindow. */
public boolean isDisplayedHyperStack() {
return win!=null && win instanceof StackWindow && ((StackWindow)win).isHyperStack();
}
/** Returns the number of channels. */
public int getNChannels() {
verifyDimensions();
return nChannels;
}
/** Returns the image depth (number of z-slices). */
public int getNSlices() {
//IJ.log("getNSlices: "+ nChannels+" "+nSlices+" "+nFrames);
verifyDimensions();
return nSlices;
}
/** Returns the number of frames (time-points). */
public int getNFrames() {
verifyDimensions();
return nFrames;
}
/** Returns the dimensions of this image (width, height, nChannels,
nSlices, nFrames) as a 5 element int array. */
public int[] getDimensions() {
verifyDimensions();
int[] d = new int[5];
d[0] = width;
d[1] = height;
d[2] = nChannels;
d[3] = nSlices;
d[4] = nFrames;
return d;
}
void verifyDimensions() {
int stackSize = getImageStackSize();
if (nSlices==1) {
if (nChannels>1 && nFrames==1)
nChannels = stackSize;
else if (nFrames>1 && nChannels==1)
nFrames = stackSize;
}
if (nChannels*nSlices*nFrames!=stackSize) {
nSlices = stackSize;
nChannels = 1;
nFrames = 1;
}
}
/** Returns the current image type (ImagePlus.GRAY8, ImagePlus.GRAY16,
ImagePlus.GRAY32, ImagePlus.COLOR_256 or ImagePlus.COLOR_RGB).
@see #getBitDepth
*/
public int getType() {
return imageType;
}
/** Returns the bit depth, 8, 16, 24 (RGB) or 32. RGB images actually use 32 bits per pixel. */
public int getBitDepth() {
int bitDepth = 0;
switch (imageType) {
case GRAY8: case COLOR_256: bitDepth=8; break;
case GRAY16: bitDepth=16; break;
case GRAY32: bitDepth=32; break;
case COLOR_RGB: bitDepth=24; break;
}
return bitDepth;
}
/** Returns the number of bytes per pixel. */
public int getBytesPerPixel() {
switch (imageType) {
case GRAY16: return 2;
case GRAY32: case COLOR_RGB: return 4;
default: return 1;
}
}
protected void setType(int type) {
if ((type<0) || (type>COLOR_RGB))
return;
int previousType = imageType;
imageType = type;
if (imageType!=previousType) {
if (win!=null)
Menus.updateMenus();
getLocalCalibration().setImage(this);
}
}
/** Adds a key-value pair to this image's properties. The key
is removed from the properties table if value is null. */
public void setProperty(String key, Object value) {
if (properties==null)
properties = new Properties();
if (value==null)
properties.remove(key);
else
properties.put(key, value);
}
/** Returns the property associated with 'key'. May return null. */
public Object getProperty(String key) {
if (properties==null)
return null;
else
return properties.get(key);
}
/** Returns this image's Properties. May return null. */
public Properties getProperties() {
return properties;
}
/** Creates a LookUpTable object that corresponds to this image. */
public LookUpTable createLut() {
ImageProcessor ip2 = getProcessor();
if (ip2!=null)
return new LookUpTable(ip2.getColorModel());
else
return new LookUpTable(LookUpTable.createGrayscaleColorModel(false));
}
/** Returns true is this image uses an inverting LUT that
displays zero as white and 255 as black. */
public boolean isInvertedLut() {
if (ip==null) {
if (img==null)
return false;
setupProcessor();
}
return ip.isInvertedLut();
}
private int[] pvalue = new int[4];
/**
Returns the pixel value at (x,y) as a 4 element array. Grayscale values
are retuned in the first element. RGB values are returned in the first
3 elements. For indexed color images, the RGB values are returned in the
first 3 three elements and the index (0-255) is returned in the last.
*/
public int[] getPixel(int x, int y) {
pvalue[0]=pvalue[1]=pvalue[2]=pvalue[3]=0;
switch (imageType) {
case GRAY8: case COLOR_256:
int index;
if (ip!=null)
index = ip.getPixel(x, y);
else {
byte[] pixels8;
if (img==null) return pvalue;
PixelGrabber pg = new PixelGrabber(img,x,y,1,1,false);
try {pg.grabPixels();}
catch (InterruptedException e){return pvalue;};
pixels8 = (byte[])(pg.getPixels());
index = pixels8!=null?pixels8[0]&0xff:0;
}
if (imageType!=COLOR_256) {
pvalue[0] = index;
return pvalue;
}
pvalue[3] = index;
// fall through to get rgb values
case COLOR_RGB:
int c = 0;
if (imageType==COLOR_RGB && ip!=null)
c = ip.getPixel(x, y);
else {
int[] pixels32 = new int[1];
if (img==null) return pvalue;
PixelGrabber pg = new PixelGrabber(img, x, y, 1, 1, pixels32, 0, width);
try {pg.grabPixels();}
catch (InterruptedException e) {return pvalue;};
c = pixels32[0];
}
int r = (c&0xff0000)>>16;
int g = (c&0xff00)>>8;
int b = c&0xff;
pvalue[0] = r;
pvalue[1] = g;
pvalue[2] = b;
break;
case GRAY16: case GRAY32:
if (ip!=null) pvalue[0] = ip.getPixel(x, y);
break;
}
return pvalue;
}
/** Returns an empty image stack that has the same
width, height and color table as this image. */
public ImageStack createEmptyStack() {
ColorModel cm;
if (ip!=null)
cm = ip.getColorModel();
else
cm = createLut().getColorModel();
return new ImageStack(width, height, cm);
}
/** Returns the image stack. The stack may have only
one slice. After adding or removing slices, call
<code>setStack()</code> to update the image and
the window that is displaying it.
@see #setStack
*/
public ImageStack getStack() {
ImageStack s;
if (stack==null) {
s = createEmptyStack();
ImageProcessor ip2 = getProcessor();
if (ip2==null)
return s;
String info = (String)getProperty("Info");
String label = info!=null?getTitle()+"\n"+info:null;
s.addSlice(label, ip2);
s.update(ip2);
} else {
s = stack;
if (ip!=null) {
Calibration cal = getCalibration();
if (cal.calibrated())
ip.setCalibrationTable(cal.getCTable());
else
ip.setCalibrationTable(null);
}
s.update(ip);
}
if (roi!=null)
s.setRoi(roi.getBounds());
else
s.setRoi(null);
return s;
}
/** Returns the base image stack. */
public ImageStack getImageStack() {
if (stack==null)
return getStack();
else {
stack.update(ip);
return stack;
}
}
/** Returns the current stack slice number or 1 if
this is a single image. */
public int getCurrentSlice() {
if (currentSlice<1) setCurrentSlice(1);
if (currentSlice>getStackSize()) setCurrentSlice(getStackSize());
return currentSlice;
}
final void setCurrentSlice(int slice) {
currentSlice = slice;
int stackSize = getStackSize();
if (nChannels==stackSize) updatePosition(currentSlice, 1, 1);
if (nSlices==stackSize) updatePosition(1, currentSlice, 1);
if (nFrames==stackSize) updatePosition(1, 1, currentSlice);
}
public int getChannel() {
return position[0];
}
public int getSlice() {
return position[1];
}
public int getFrame() {
return position[2];
}
public void killStack() {
stack = null;
trimProcessor();
}
/** Sets the current hyperstack position and updates the display,
where 'channel', 'slice' and 'frame' are one-based indexes. */
public void setPosition(int channel, int slice, int frame) {
//IJ.log("setPosition: "+channel+" "+slice+" "+frame+" "+noUpdateMode);
verifyDimensions();
if (channel<1) channel = 1;
if (channel>nChannels) channel = nChannels;
if (slice<1) slice = 1;
if (slice>nSlices) slice = nSlices;
if (frame<1) frame = 1;
if (frame>nFrames) frame = nFrames;
if (isDisplayedHyperStack())
((StackWindow)win).setPosition(channel, slice, frame);
else {
setSlice((frame-1)*nChannels*nSlices + (slice-1)*nChannels + channel);
updatePosition(channel, slice, frame);
}
}
/** Sets the current hyperstack position without updating the display,
where 'channel', 'slice' and 'frame' are one-based indexes. */
public void setPositionWithoutUpdate(int channel, int slice, int frame) {
noUpdateMode = true;
setPosition(channel, slice, frame);
noUpdateMode = false;
}
/** Returns that stack index (one-based) corresponding to the specified position. */
public int getStackIndex(int channel, int slice, int frame) {
if (channel<1) channel = 1;
if (channel>nChannels) channel = nChannels;
if (slice<1) slice = 1;
if (slice>nSlices) slice = nSlices;
if (frame<1) frame = 1;
if (frame>nFrames) frame = nFrames;
return (frame-1)*nChannels*nSlices + (slice-1)*nChannels + channel;
}
/* Hack needed to make the HyperStackReducer work. */
public void resetStack() {
if (currentSlice==1 && stack!=null && stack.getSize()>0) {
ColorModel cm = ip.getColorModel();
double min = ip.getMin();
double max = ip.getMax();
ip = stack.getProcessor(1);
ip.setColorModel(cm);
ip.setMinAndMax(min, max);
}
}
/** Set the current hyperstack position based on the stack index 'n' (one-based). */
public void setPosition(int n) {
int[] pos = convertIndexToPosition(n);
setPosition(pos[0], pos[1], pos[2]);
}
/** Converts the stack index 'n' (one-based) into a hyperstack position (channel, slice, frame). */
public int[] convertIndexToPosition(int n) {
if (n<1 || n>getStackSize())
throw new IllegalArgumentException("n out of range: "+n);
int[] position = new int[3];
int[] dim = getDimensions();
position[0] = ((n-1)%dim[2])+1;
position[1] = (((n-1)/dim[2])%dim[3])+1;
position[2] = (((n-1)/(dim[2]*dim[3]))%dim[4])+1;
return position;
}
/** Displays the specified stack image, where 1<=n<=stackSize.
Does nothing if this image is not a stack. */
public synchronized void setSlice(int n) {
if (stack==null || (n==currentSlice&&ip!=null)) {
if (!noUpdateMode)
updateAndRepaintWindow();
return;
}
if (n>=1 && n<=stack.getSize()) {
Roi roi = getRoi();
if (roi!=null)
roi.endPaste();
if (isProcessor())
stack.setPixels(ip.getPixels(),currentSlice);
ip = getProcessor();
setCurrentSlice(n);
Object pixels = stack.getPixels(currentSlice);
if (ip!=null && pixels!=null) {
ip.setSnapshotPixels(null);
ip.setPixels(pixels);
} else
ip = stack.getProcessor(n);
if (win!=null && win instanceof StackWindow)
((StackWindow)win).updateSliceSelector();
//if (IJ.altKeyDown() && !IJ.isMacro()) {
// if (imageType==GRAY16 || imageType==GRAY32) {
// ip.resetMinAndMax();
// IJ.showStatus(n+": min="+ip.getMin()+", max="+ip.getMax());
// }
// ContrastAdjuster.update();
//}
if (imageType==COLOR_RGB)
ContrastAdjuster.update();
if (!noUpdateMode)
updateAndRepaintWindow();
else
img = null;
}
}
/** Displays the specified stack image (1<=n<=stackSize)
without updating the display. */
public void setSliceWithoutUpdate(int n) {
noUpdateMode = true;
setSlice(n);
noUpdateMode = false;
}
/** Returns the current selection, or null if there is no selection. */
public Roi getRoi() {
return roi;
}
/** Assigns the specified ROI to this image and displays it. Any existing
ROI is deleted if <code>roi</code> is null or its width or height is zero. */
public void setRoi(Roi newRoi) {
setRoi(newRoi, true);
}
/** Assigns 'newRoi' to this image and displays it if 'updateDisplay' is true. */
public void setRoi(Roi newRoi, boolean updateDisplay) {
if (newRoi==null)
{killRoi(); return;}
if (newRoi.isVisible()) {
newRoi = (Roi)newRoi.clone();
if (newRoi==null)
{killRoi(); return;}
}
Rectangle bounds = newRoi.getBounds();
if (bounds.width==0 && bounds.height==0 && !(newRoi.getType()==Roi.POINT||newRoi.getType()==Roi.LINE))
{killRoi(); return;}
roi = newRoi;
if (ip!=null) {
ip.setMask(null);
if (roi.isArea())
ip.setRoi(bounds);
else
ip.resetRoi();
}
roi.setImage(this);
if (updateDisplay) draw();
}
/** Creates a rectangular selection. */
public void setRoi(int x, int y, int width, int height) {
setRoi(new Rectangle(x, y, width, height));
}
/** Creates a rectangular selection. */
public void setRoi(Rectangle r) {
setRoi(new Roi(r.x, r.y, r.width, r.height));
}
/** Starts the process of creating a new selection, where sx and sy are the
starting screen coordinates. The selection type is determined by which tool in
the tool bar is active. The user interactively sets the selection size and shape. */
public void createNewRoi(int sx, int sy) {
killRoi();
switch (Toolbar.getToolId()) {
case Toolbar.RECTANGLE:
int cornerDiameter = Toolbar.getRoundRectArcSize();
roi = new Roi(sx, sy, this, cornerDiameter);
if (cornerDiameter>0) {
roi.setStrokeColor(Toolbar.getForegroundColor());
roi.setStrokeWidth(RectToolOptions.getDefaultStrokeWidth());
}
break;
case Toolbar.OVAL:
if (Toolbar.getOvalToolType()==Toolbar.ELLIPSE_ROI)
roi = new EllipseRoi(sx, sy, this);
else
roi = new OvalRoi(sx, sy, this);
break;
case Toolbar.POLYGON:
case Toolbar.POLYLINE:
case Toolbar.ANGLE:
roi = new PolygonRoi(sx, sy, this);
break;
case Toolbar.FREEROI:
case Toolbar.FREELINE:
roi = new FreehandRoi(sx, sy, this);
break;
case Toolbar.LINE:
if ("arrow".equals(Toolbar.getToolName()))
roi = new Arrow(sx, sy, this);
else
roi = new Line(sx, sy, this);
break;
case Toolbar.TEXT:
roi = new TextRoi(sx, sy, this);
break;
case Toolbar.POINT:
roi = new PointRoi(sx, sy, this);
if (Prefs.pointAutoMeasure || (Prefs.pointAutoNextSlice&&!Prefs.pointAddToManager)) IJ.run("Measure");
if (Prefs.pointAddToManager) {
IJ.run("Add to Manager ");
ImageCanvas ic = getCanvas();
if (ic!=null && !ic.getShowAllROIs())
ic.setShowAllROIs(true);
}
if (Prefs.pointAutoNextSlice && getStackSize()>1) {
IJ.run("Next Slice [>]");
killRoi();
}
break;
}
}
/** Deletes the current region of interest. Makes a copy
of the current ROI so it can be recovered by the
Edit/Selection/Restore Selection command. */
public void killRoi() {
if (roi!=null) {
saveRoi();
roi = null;
if (ip!=null)
ip.resetRoi();
draw();
}
}
public void saveRoi() {
if (roi!=null) {
roi.endPaste();
Rectangle r = roi.getBounds();
if ((r.width>0 || r.height>0)) {
Roi.previousRoi = (Roi)roi.clone();
if (IJ.debugMode) IJ.log("saveRoi: "+roi);
}
}
}
public void restoreRoi() {
if (Roi.previousRoi!=null) {
Roi pRoi = Roi.previousRoi;
Rectangle r = pRoi.getBounds();
if (r.width<=width || r.height<=height || isSmaller(pRoi)) { // will it (mostly) fit in this image?
roi = (Roi)pRoi.clone();
roi.setImage(this);
if (r.x>=width || r.y>=height || (r.x+r.width)<=0 || (r.y+r.height)<=0) // does it need to be moved?
roi.setLocation((width-r.width)/2, (height-r.height)/2);
else if (r.width==width && r.height==height) // is it the same size as the image
roi.setLocation(0, 0);
draw();
}
}
}
boolean isSmaller(Roi r) {
ImageProcessor mask = r.getMask();
if (mask==null) return false;
mask.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE);
ImageStatistics stats = ImageStatistics.getStatistics(mask, MEAN+LIMIT, null);
return stats.area<=width*height;
}
/** Implements the File/Revert command. */
public void revert() {
if (getStackSize()>1 && getStack().isVirtual())
return;
FileInfo fi = getOriginalFileInfo();
boolean isFileInfo = fi!=null && fi.fileFormat!=FileInfo.UNKNOWN;
if (!(isFileInfo || url!=null))
return;
if (ij!=null && changes && isFileInfo && !Interpreter.isBatchMode() && !IJ.isMacro() && !IJ.altKeyDown()) {
if (!IJ.showMessageWithCancel("Revert?", "Revert to saved version of\n\""+getTitle()+"\"?"))
return;
}
Roi saveRoi = null;
if (roi!=null) {
roi.endPaste();
saveRoi = (Roi)roi.clone();
}
if (getStackSize()>1) {
revertStack(fi);
return;
}
trimProcessor();
if (isFileInfo && !(url!=null&&(fi.directory==null||fi.directory.equals(""))))
new FileOpener(fi).revertToSaved(this);
else if (url!=null) {
IJ.showStatus("Loading: " + url);
Opener opener = new Opener();
try {
ImagePlus imp = opener.openURL(url);
if (imp!=null)
setProcessor(null, imp.getProcessor());
} catch (Exception e) {}
if (getType()==COLOR_RGB && getTitle().endsWith(".jpg"))
Opener.convertGrayJpegTo8Bits(this);
}
if (Prefs.useInvertingLut && getBitDepth()==8 && ip!=null && !ip.isInvertedLut()&& !ip.isColorLut())
invertLookupTable();
if (getProperty("FHT")!=null) {
properties.remove("FHT");
if (getTitle().startsWith("FFT of "))
setTitle(getTitle().substring(7));
}
ContrastAdjuster.update();
if (saveRoi!=null) setRoi(saveRoi);
repaintWindow();
IJ.showStatus("");
changes = false;
notifyListeners(UPDATED);
}
void revertStack(FileInfo fi) {
String path = null;
String url2 = null;
if (url!=null && !url.equals("")) {
path = url;
url2 = url;
} else if (fi!=null && !((fi.directory==null||fi.directory.equals("")))) {
path = fi.directory+fi.fileName;
} else if (fi!=null && fi.url!=null && !fi.url.equals("")) {
path = fi.url;
url2 = fi.url;
} else
return;
//IJ.log("revert: "+path+" "+fi);
IJ.showStatus("Loading: " + path);
ImagePlus imp = IJ.openImage(path);
if (imp!=null) {
int n = imp.getStackSize();
int c = imp.getNChannels();
int z = imp.getNSlices();
int t = imp.getNFrames();
if (z==n || t==n || (c==getNChannels()&&z==getNSlices()&&t==getNFrames())) {
setCalibration(imp.getCalibration());
setStack(imp.getStack(), c, z, t);
} else {
ImageWindow win = getWindow();
Point loc = null;
if (win!=null) loc = win.getLocation();
changes = false;
close();
FileInfo fi2 = imp.getOriginalFileInfo();
if (fi2!=null && (fi2.url==null || fi2.url.length()==0)) {
fi2.url = url2;
imp.setFileInfo(fi2);
}
ImageWindow.setNextLocation(loc);
imp.show();
}
}
}
/** Returns a FileInfo object containing information, including the
pixel array, needed to save this image. Use getOriginalFileInfo()
to get a copy of the FileInfo object used to open the image.
@see ij.io.FileInfo
@see #getOriginalFileInfo
@see #setFileInfo
*/
public FileInfo getFileInfo() {
FileInfo fi = new FileInfo();
fi.width = width;
fi.height = height;
fi.nImages = getStackSize();
if (compositeImage)
fi.nImages = getImageStackSize();
fi.whiteIsZero = isInvertedLut();
fi.intelByteOrder = false;
setupProcessor();
if (fi.nImages==1)
fi.pixels = ip.getPixels();
else
fi.pixels = stack.getImageArray();
Calibration cal = getCalibration();
if (cal.scaled()) {
fi.pixelWidth = cal.pixelWidth;
fi.pixelHeight = cal.pixelHeight;
fi.unit = cal.getUnit();
}
if (fi.nImages>1)
fi.pixelDepth = cal.pixelDepth;
fi.frameInterval = cal.frameInterval;
if (cal.calibrated()) {
fi.calibrationFunction = cal.getFunction();
fi.coefficients = cal.getCoefficients();
fi.valueUnit = cal.getValueUnit();
}
switch (imageType) {
case GRAY8: case COLOR_256:
LookUpTable lut = createLut();
if (imageType==COLOR_256 || !lut.isGrayscale())
fi.fileType = FileInfo.COLOR8;
else
fi.fileType = FileInfo.GRAY8;
fi.lutSize = lut.getMapSize();
fi.reds = lut.getReds();
fi.greens = lut.getGreens();
fi.blues = lut.getBlues();
break;
case GRAY16:
if (compositeImage && fi.nImages==3)
fi.fileType = fi.RGB48;
else
fi.fileType = fi.GRAY16_UNSIGNED;
break;
case GRAY32:
fi.fileType = fi.GRAY32_FLOAT;
break;
case COLOR_RGB:
fi.fileType = fi.RGB;
break;
default:
}
return fi;
}
/** Returns the FileInfo object that was used to open this image.
Returns null for images created using the File/New command.
@see ij.io.FileInfo
@see #getFileInfo
*/
public FileInfo getOriginalFileInfo() {
if (fileInfo==null & url!=null) {
fileInfo = new FileInfo();
fileInfo.width = width;
fileInfo.height = height;
fileInfo.url = url;
fileInfo.directory = null;
}
return fileInfo;
}
/** Used by ImagePlus to monitor loading of images. */
public boolean imageUpdate(Image img, int flags, int x, int y, int w, int h) {
imageUpdateY = y;
imageUpdateW = w;
if ((flags & ERROR) != 0) {
errorLoadingImage = true;
return false;
}
imageLoaded = (flags & (ALLBITS|FRAMEBITS|ABORT)) != 0;
return !imageLoaded;
}
/** Sets the ImageProcessor, Roi, AWT Image and stack image
arrays to null. Does nothing if the image is locked. */
public synchronized void flush() {
notifyListeners(CLOSED);
if (locked || ignoreFlush) return;
ip = null;
if (roi!=null) roi.setImage(null);
roi = null;
if (stack!=null) {
Object[] arrays = stack.getImageArray();
if (arrays!=null) {
for (int i=0; i<arrays.length; i++)
arrays[i] = null;
}
}
stack = null;
img = null;
win = null;
if (roi!=null) roi.setImage(null);
roi = null;
properties = null;
calibration = null;
overlay = null;
flatteningCanvas = null;
}
public void setIgnoreFlush(boolean ignoreFlush) {
this.ignoreFlush = ignoreFlush;
}
/** Returns a copy (clone) of this ImagePlus. */
public ImagePlus duplicate() {
return (new Duplicator()).run(this);
}
/** Returns a new ImagePlus with this image's attributes
(e.g. spatial scale), but no image. */
public ImagePlus createImagePlus() {
ImagePlus imp2 = new ImagePlus();
imp2.setType(getType());
imp2.setCalibration(getCalibration());
return imp2;
}
/** Returns a new hyperstack with this image's attributes
(e.g., width, height, spatial scale), but no image data. */
public ImagePlus createHyperStack(String title, int channels, int slices, int frames, int bitDepth) {
int size = channels*slices*frames;
ImageStack stack2 = new ImageStack(width, height, size); // create empty stack
ImageProcessor ip2 = null;
switch (bitDepth) {
case 8: ip2 = new ByteProcessor(width, height); break;
case 16: ip2 = new ShortProcessor(width, height); break;
case 24: ip2 = new ColorProcessor(width, height); break;
case 32: ip2 = new FloatProcessor(width, height); break;
default: throw new IllegalArgumentException("Invalid bit depth");
}
stack2.setPixels(ip2.getPixels(), 1); // can't create ImagePlus will null 1st image
ImagePlus imp2 = new ImagePlus(title, stack2);
stack2.setPixels(null, 1);
imp2.setDimensions(channels, slices, frames);
imp2.setCalibration(getCalibration());
imp2.setOpenAsHyperStack(true);
return imp2;
}
/** Copies the calibration of the specified image to this image. */
public void copyScale(ImagePlus imp) {
if (imp!=null && globalCalibration==null)
setCalibration(imp.getCalibration());
}
/** Calls System.currentTimeMillis() to save the current
time so it can be retrieved later using getStartTime()
to calculate the elapsed time of an operation. */
public void startTiming() {
startTime = System.currentTimeMillis();
}
/** Returns the time in milliseconds when
startTiming() was last called. */
public long getStartTime() {
return startTime;
}
/** Returns this image's calibration. */
public Calibration getCalibration() {
//IJ.log("getCalibration: "+globalCalibration+" "+calibration);
if (globalCalibration!=null) {
Calibration gc = globalCalibration.copy();
gc.setImage(this);
return gc;
} else {
if (calibration==null)
calibration = new Calibration(this);
return calibration;
}
}
/** Sets this image's calibration. */
public void setCalibration(Calibration cal) {
//IJ.write("setCalibration: "+cal);
if (cal==null)
calibration = null;
else {
calibration = cal.copy();
calibration.setImage(this);
}
}
/** Sets the system-wide calibration. */
public void setGlobalCalibration(Calibration global) {
//IJ.log("setGlobalCalibration ("+getTitle()+"): "+global);
if (global==null)
globalCalibration = null;
else
globalCalibration = global.copy();
}
/** Returns the system-wide calibration, or null. */
public Calibration getGlobalCalibration() {
return globalCalibration;
}
/** Returns this image's local calibration, ignoring
the "Global" calibration flag. */
public Calibration getLocalCalibration() {
if (calibration==null)
calibration = new Calibration(this);
return calibration;
}
/** Displays the cursor coordinates and pixel value in the status bar.
Called by ImageCanvas when the mouse moves. Can be overridden by
ImagePlus subclasses.
*/
public void mouseMoved(int x, int y) {
if (ij!=null)
ij.showStatus(getLocationAsString(x,y) + getValueAsString(x,y));
savex=x; savey=y;
}
private int savex, savey;
/** Redisplays the (x,y) coordinates and pixel value (which may
have changed) in the status bar. Called by the Next Slice and
Previous Slice commands to update the z-coordinate and pixel value.
*/
public void updateStatusbarValue() {
IJ.showStatus(getLocationAsString(savex,savey) + getValueAsString(savex,savey));
}
String getFFTLocation(int x, int y, Calibration cal) {
double center = width/2.0;
double r = Math.sqrt((x-center)*(x-center) + (y-center)*(y-center));
if (r<1.0) r = 1.0;
double theta = Math.atan2(y-center, x-center);
theta = theta*180.0/Math.PI;
if (theta<0) theta = 360.0+theta;
String s = "r=";
if (cal.scaled())
s += IJ.d2s((width/r)*cal.pixelWidth,2) + " " + cal.getUnit() + "/c (" + IJ.d2s(r,0) + ")";
else
s += IJ.d2s(width/r,2) + " p/c (" + IJ.d2s(r,0) + ")";
s += ", theta= " + IJ.d2s(theta,2) + IJ.degreeSymbol;
return s;
}
/** Converts the current cursor location to a string. */
public String getLocationAsString(int x, int y) {
Calibration cal = getCalibration();
if (getProperty("FHT")!=null)
return getFFTLocation(x, height-y-1, cal);
//y = Analyzer.updateY(y, height);
if (!IJ.altKeyDown()) {
String s = " x="+d2s(cal.getX(x)) + ", y=" + d2s(cal.getY(y,height));
if (getStackSize()>1) {
int z = isDisplayedHyperStack()?getSlice()-1:getCurrentSlice()-1;
s += ", z="+d2s(cal.getZ(z));
}
return s;
} else {
String s = " x="+x+", y=" + y;
if (getStackSize()>1) {
int z = isDisplayedHyperStack()?getSlice()-1:getCurrentSlice()-1;
s += ", z=" + z;
}
return s;
}
}
private String d2s(double n) {
return n==(int)n?Integer.toString((int)n):IJ.d2s(n);
}
private String getValueAsString(int x, int y) {
if (win!=null && win instanceof PlotWindow)
return "";
Calibration cal = getCalibration();
int[] v = getPixel(x, y);
int type = getType();
switch (type) {
case GRAY8: case GRAY16: case COLOR_256:
if (type==COLOR_256) {
if (cal.getCValue(v[3])==v[3]) // not calibrated
return(", index=" + v[3] + ", value=" + v[0] + "," + v[1] + "," + v[2]);
else
v[0] = v[3];
}
double cValue = cal.getCValue(v[0]);
if (cValue==v[0])
return(", value=" + v[0]);
else
return(", value=" + IJ.d2s(cValue) + " ("+v[0]+")");
case GRAY32:
return(", value=" + Float.intBitsToFloat(v[0]));
case COLOR_RGB:
return(", value=" + v[0] + "," + v[1] + "," + v[2]);
default: return("");
}
}
/** Copies the contents of the current selection to the internal clipboard.
Copies the entire image if there is no selection. Also clears
the selection if <code>cut</code> is true. */
public void copy(boolean cut) {
Roi roi = getRoi();
if (roi!=null && !roi.isArea()) {
IJ.error("Cut/Copy", "The Cut and Copy commands require\n"
+"an area selection, or no selection.");
return;
}
boolean batchMode = Interpreter.isBatchMode();
String msg = (cut)?"Cutt":"Copy";
if (!batchMode) IJ.showStatus(msg+ "ing...");
ImageProcessor ip = getProcessor();
ImageProcessor ip2;
Roi roi2 = null;
ip2 = ip.crop();
if (roi!=null && roi.getType()!=Roi.RECTANGLE) {
roi2 = (Roi)roi.clone();
Rectangle r = roi.getBounds();
if (r.x<0 || r.y<0 || r.x+r.width>width || r.y+r.height>height) {
roi2 = new ShapeRoi(roi2);
ShapeRoi image = new ShapeRoi(new Roi(0, 0, width, height));
roi2 = image.and((ShapeRoi)roi2);
}
}
clipboard = new ImagePlus("Clipboard", ip2);
if (roi2!=null) clipboard.setRoi(roi2);
if (cut) {
ip.snapshot();
ip.setColor(Toolbar.getBackgroundColor());
ip.fill();
if (roi!=null && roi.getType()!=Roi.RECTANGLE) {
getMask();
ip.reset(ip.getMask());
} setColor(Toolbar.getForegroundColor());
Undo.setup(Undo.FILTER, this);
updateAndDraw();
}
int bytesPerPixel = 1;
switch (clipboard.getType()) {
case ImagePlus.GRAY16: bytesPerPixel = 2; break;
case ImagePlus.GRAY32: case ImagePlus.COLOR_RGB: bytesPerPixel = 4;
}
//Roi roi3 = clipboard.getRoi();
//IJ.log("copy: "+clipboard +" "+ "roi3="+(roi3!=null?""+roi3:""));
if (!batchMode) {
msg = (cut)?"Cut":"Copy";
IJ.showStatus(msg + ": " + (clipboard.getWidth()*clipboard.getHeight()*bytesPerPixel)/1024 + "k");
}
}
/** Inserts the contents of the internal clipboard into the active image. If there
is a selection the same size as the image on the clipboard, the image is inserted
into that selection, otherwise the selection is inserted into the center of the image.*/
public void paste() {
if (clipboard==null) return;
int cType = clipboard.getType();
int iType = getType();
int w = clipboard.getWidth();
int h = clipboard.getHeight();
Roi cRoi = clipboard.getRoi();
Rectangle r = null;
Roi roi = getRoi();
if (roi!=null)
r = roi.getBounds();
//if (w==width && h==height && (r==null||w!=r.width||h!=r.height)) {
// setRoi(0, 0, width, height);
// roi = getRoi();
// r = roi.getBounds();
//}
if (r==null || (r!=null && (w!=r.width || h!=r.height))) {
// create a new roi centered on visible part of image
ImageCanvas ic = null;
if (win!=null)
ic = win.getCanvas();
Rectangle srcRect = ic!=null?ic.getSrcRect():new Rectangle(0,0,width, height);
int xCenter = srcRect.x + srcRect.width/2;
int yCenter = srcRect.y + srcRect.height/2;
if (cRoi!=null && cRoi.getType()!=Roi.RECTANGLE) {
cRoi.setImage(this);
cRoi.setLocation(xCenter-w/2, yCenter-h/2);
setRoi(cRoi);
} else
setRoi(xCenter-w/2, yCenter-h/2, w, h);
roi = getRoi();
}
if (IJ.isMacro()) {
//non-interactive paste
int pasteMode = Roi.getCurrentPasteMode();
boolean nonRect = roi.getType()!=Roi.RECTANGLE;
ImageProcessor ip = getProcessor();
if (nonRect) ip.snapshot();
r = roi.getBounds();
ip.copyBits(clipboard.getProcessor(), r.x, r.y, pasteMode);
if (nonRect) ip.reset(getMask());
updateAndDraw();
//killRoi();
} else if (roi!=null) {
roi.startPaste(clipboard);
Undo.setup(Undo.PASTE, this);
}
changes = true;
}
/** Returns the internal clipboard or null if the internal clipboard is empty. */
public static ImagePlus getClipboard() {
return clipboard;
}
/** Clears the internal clipboard. */
public static void resetClipboard() {
clipboard = null;
}
protected void notifyListeners(int id) {
synchronized (listeners) {
for (int i=0; i<listeners.size(); i++) {
ImageListener listener = (ImageListener)listeners.elementAt(i);
switch (id) {
case OPENED:
listener.imageOpened(this);
break;
case CLOSED:
listener.imageClosed(this);
break;
case UPDATED:
listener.imageUpdated(this);
break;
}
}
}
}
public static void addImageListener(ImageListener listener) {
listeners.addElement(listener);
}
public static void removeImageListener(ImageListener listener) {
listeners.removeElement(listener);
}
/** Returns 'true' if the image is locked. */
public boolean isLocked() {
return locked;
}
public void setOpenAsHyperStack(boolean openAsHyperStack) {
this.openAsHyperStack = openAsHyperStack;
}
public boolean getOpenAsHyperStack() {
return openAsHyperStack;
}
/** Returns true if this is a CompositeImage. */
public boolean isComposite() {
return compositeImage && nChannels>=1 && (this instanceof CompositeImage);
}
/** Sets the display range of the current channel. With non-composite
images it is identical to ip.setMinAndMax(min, max). */
public void setDisplayRange(double min, double max) {
if (ip!=null)
ip.setMinAndMax(min, max);
}
public double getDisplayRangeMin() {
return ip.getMin();
}
public double getDisplayRangeMax() {
return ip.getMax();
}
/** Sets the display range of specified channels in an RGB image, where 4=red,
2=green, 1=blue, 6=red+green, etc. With non-RGB images, this method is
identical to setDisplayRange(min, max). This method is used by the
Image/Adjust/Color Balance tool . */
public void setDisplayRange(double min, double max, int channels) {
if (ip instanceof ColorProcessor)
((ColorProcessor)ip).setMinAndMax(min, max, channels);
else
ip.setMinAndMax(min, max);
}
public void resetDisplayRange() {
if (imageType==GRAY16 && default16bitDisplayRange>=8 && default16bitDisplayRange<=16 && !(getCalibration().isSigned16Bit())) {
ip.setMinAndMax(0, Math.pow(2,default16bitDisplayRange)-1);
} else
ip.resetMinAndMax();
}
/** Set the default 16-bit display range, where 'bitDepth' must be 0 (auto-scaling),
8 (0-255), 10 (0-1023), 12 (0-4095, 15 (0-32767) or 16 (0-65535). */
public static void setDefault16bitRange(int bitDepth) {
if (!(bitDepth==8 || bitDepth==10 || bitDepth==12 || bitDepth==15 || bitDepth==16))
bitDepth = 0;
default16bitDisplayRange = bitDepth;
}
/** Returns the default 16-bit display range, 0 (auto-scaling), 8, 10, 12, 15 or 16. */
public static int getDefault16bitRange() {
return default16bitDisplayRange;
}
public void updatePosition(int c, int z, int t) {
//IJ.log("updatePosition: "+c+", "+z+", "+t);
position[0] = c;
position[1] = z;
position[2] = t;
}
/** Returns a "flattened" version of this image, in RGB format. */
public ImagePlus flatten() {
ImagePlus imp2 = createImagePlus();
String title = "Flat_"+getTitle();
ImageCanvas ic2 = new ImageCanvas(imp2);
imp2.flatteningCanvas = ic2;
imp2.setRoi(getRoi());
ImageCanvas ic = getCanvas();
Overlay overlay2 = getOverlay();
ic2.setOverlay(overlay2);
if (ic!=null) {
ic2.setShowAllROIs(ic.getShowAllROIs());
//double mag = ic.getMagnification();
//if (mag<1.0) ic2.setMagnification(mag);
}
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.getGraphics();
g.drawImage(getImage(), 0, 0, null);
ic2.paint(g);
imp2.flatteningCanvas = null;
if (Recorder.record) Recorder.recordCall("imp = IJ.getImage().flatten();");
return new ImagePlus(title, new ColorProcessor(bi));
}
/** Installs a list of ROIs that will be drawn on this image as a non-destructive overlay.
* @see ij.gui.Roi#setStrokeColor
* @see ij.gui.Roi#setStrokeWidth
* @see ij.gui.Roi#setFillColor
* @see ij.gui.Roi#setLocation
* @see ij.gui.Roi#setNonScalable
*/
public void setOverlay(Overlay overlay) {
ImageCanvas ic = getCanvas();
if (ic!=null) {
ic.setOverlay(overlay);
overlay = null;
} else
this.overlay = overlay;
setHideOverlay(false);
}
/** Creates an Overlay from the specified Shape, Color
* and BasicStroke, and assigns it to this image.
* @see #setOverlay(ij.gui.Overlay)
* @see ij.gui.Roi#setStrokeColor
* @see ij.gui.Roi#setStrokeWidth
*/
public void setOverlay(Shape shape, Color color, BasicStroke stroke) {
if (shape==null)
{setOverlay(null); return;}
Roi roi = new ShapeRoi(shape);
roi.setStrokeColor(color);
roi.setStroke(stroke);
setOverlay(new Overlay(roi));
}
/** Creates an Overlay from the specified ROI, and assigns it to this image.
* @see #setOverlay(ij.gui.Overlay)
*/
public void setOverlay(Roi roi, Color strokeColor, int strokeWidth, Color fillColor) {
roi.setStrokeColor(strokeColor);
roi.setStrokeWidth(strokeWidth);
roi.setFillColor(fillColor);
setOverlay(new Overlay(roi));
}
/** Returns the current overly, or null if this image does not have an overlay. */
public Overlay getOverlay() {
ImageCanvas ic = getCanvas();
if (ic!=null)
return ic.getOverlay();
else
return overlay;
}
public void setHideOverlay(boolean hide) {
hideOverlay = hide;
ImageCanvas ic = getCanvas();
if (ic!=null && ic.getOverlay()!=null)
ic.repaint();
}
public boolean getHideOverlay() {
return hideOverlay;
}
/** Returns a shallow copy of this ImagePlus. */
public synchronized Object clone() {
try {
ImagePlus copy = (ImagePlus)super.clone();
copy.win = null;
return copy;
} catch (CloneNotSupportedException e) {
return null;
}
}
public String toString() {
return "imp["+getTitle()+" "+width+"x"+height+"x"+getStackSize()+"]";
}
}
|