Esempio n. 1
0
 void loadParticleResults(String filename, ResultsTable res) {
   try {
     String line;
     FileReader fr = new FileReader(filename);
     BufferedReader br = new BufferedReader(fr);
     java.lang.String header =
         " 	Intensity	X (px)	Y (px)	X (nm)	Y (nm)	Z (nm)	Left-Width(px)	Right-Width (px)	Up-Height (px)	Down-Height (px)	X Symmetry (%)	Y Symmetry (%)	Width minus Height (px)	Frame Number";
     java.lang.String firstline = br.readLine();
     if (!firstline.contains("X (px)	Y (px)	X (nm)	Y (nm)	Z (nm)")) {
       IJ.error("File does not seam to be a Particles Table file");
       IJ.log("Found header: " + firstline);
       IJ.log("Expecting: " + header);
       return;
     }
     res.reset();
     int counter = 1;
     java.util.concurrent.locks.Lock lock = new java.util.concurrent.locks.ReentrantLock();
     ThreadedLoader tloader = new ThreadedLoader();
     // java.lang.String txt = fr.read();
     while ((line = br.readLine()) != null) {
       tloader = new ThreadedLoader();
       tloader.mysetup(res, lock, line);
       tloader.start();
       IJ.showStatus("Loading particle " + counter + "... sit back and relax.");
       counter++;
     }
     try {
       tloader.join();
     } catch (Exception e) {
       IJ.error("" + e);
     }
     if (res.getCounter() < 5000000) {
       IJ.showStatus("Creating particle table, this should take a few seconds...");
       res.show("Results");
     } else
       IJ.showMessage(
           "Warning",
           "Results table has too many particles, they will not be shown but the data still exists within it\nyou can still use all the plugin functionality or save table changes though the 'Save Particle Table' command.");
     fr.close();
     IJ.showStatus("Done loading table...");
   } catch (FileNotFoundException e) {
     IJ.error("File not found exception" + e);
     return;
   } catch (IOException e) {
     IJ.error("IOException exception" + e);
     return;
   } catch (NumberFormatException e) {
     IJ.error("Number format exception" + e);
     return;
   }
 }
Esempio n. 2
0
 /** Overrides ImagePlus.show(). * */
 public void show() {
   if (img == null && ip != null) img = ip.createImage();
   ImageWindow.centerNextImage();
   win = new ImageWindow(this, new ColorCanvas(this));
   draw();
   IJ.showStatus("");
 }
Esempio n. 3
0
 void loadTransformation(String filename, ResultsTable res) {
   try {
     String line;
     FileReader fr = new FileReader(filename);
     BufferedReader br = new BufferedReader(fr);
     if (!br.readLine().equals(" 	Z-Step	Raw Width minus Heigh	Calibration Width minus Height")) {
       IJ.error("File does not seam to be an Astigmatism calibration file");
       return;
     }
     // java.lang.String [] elements = new java.lang.String [3];
     java.lang.String[] elements;
     int counter = 1;
     res.reset();
     while ((line = br.readLine()) != null) {
       IJ.showStatus("Loading element " + counter + "... sit back and relax.");
       counter++;
       line.trim();
       elements = line.split("\t");
       res.incrementCounter();
       res.addValue("Z-Step", Double.parseDouble(elements[1]));
       res.addValue("Raw Width minus Heigh", Double.parseDouble(elements[2]));
       res.addValue("Calibration Width minus Height", Double.parseDouble(elements[3]));
     }
     fr.close();
   } catch (FileNotFoundException e) {
     IJ.error("File not found exception" + e);
     return;
   } catch (IOException e) {
     IJ.error("IOException exception" + e);
     return;
   } catch (NumberFormatException e) {
     IJ.error("Number format exception" + e);
     return;
   }
 }
Esempio n. 4
0
    public synchronized void adjustmentValueChanged(AdjustmentEvent e) {

      if (!checkImage()) {
        IJ.beep();
        IJ.showStatus("No Image");
        return;
      }

      if (e.getSource() == minSlider) {
        adjustMinHue((int) minSlider.getValue());
      } else if (e.getSource() == maxSlider) {
        adjustMaxHue((int) maxSlider.getValue());
      } else if (e.getSource() == minSlider2) {
        adjustMinSat((int) minSlider2.getValue());
      } else if (e.getSource() == maxSlider2) {
        adjustMaxSat((int) maxSlider2.getValue());
      } else if (e.getSource() == minSlider3) {
        adjustMinBri((int) minSlider3.getValue());
      } else if (e.getSource() == maxSlider3) {
        adjustMaxBri((int) maxSlider3.getValue());
      }
      originalB.setEnabled(true);
      updateLabels();
      updatePlot();
      notify();
    }
Esempio n. 5
0
 void createEllipse(ImagePlus imp) {
   IJ.showStatus("Fitting ellipse");
   Roi roi = imp.getRoi();
   if (roi == null) {
     noRoi("Fit Ellipse");
     return;
   }
   if (roi.isLine()) {
     IJ.error("Fit Ellipse", "\"Fit Ellipse\" does not work with line selections");
     return;
   }
   ImageProcessor ip = imp.getProcessor();
   ip.setRoi(roi);
   int options = Measurements.CENTROID + Measurements.ELLIPSE;
   ImageStatistics stats = ImageStatistics.getStatistics(ip, options, null);
   double dx = stats.major * Math.cos(stats.angle / 180.0 * Math.PI) / 2.0;
   double dy = -stats.major * Math.sin(stats.angle / 180.0 * Math.PI) / 2.0;
   double x1 = stats.xCentroid - dx;
   double x2 = stats.xCentroid + dx;
   double y1 = stats.yCentroid - dy;
   double y2 = stats.yCentroid + dy;
   double aspectRatio = stats.minor / stats.major;
   imp.killRoi();
   imp.setRoi(new EllipseRoi(x1, y1, x2, y2, aspectRatio));
 }
Esempio n. 6
0
 public void mouseMoved(MouseEvent e) {
   // if (ij==null) return;
   int sx = e.getX();
   int sy = e.getY();
   int ox = offScreenX(sx);
   int oy = offScreenY(sy);
   flags = e.getModifiers();
   setCursor(sx, sy, ox, oy);
   IJ.setInputEvent(e);
   Roi roi = imp.getRoi();
   if (roi != null
       && (roi.getType() == Roi.POLYGON
           || roi.getType() == Roi.POLYLINE
           || roi.getType() == Roi.ANGLE)
       && roi.getState() == roi.CONSTRUCTING) {
     PolygonRoi pRoi = (PolygonRoi) roi;
     pRoi.handleMouseMove(ox, oy);
   } else {
     if (ox < imageWidth && oy < imageHeight) {
       ImageWindow win = imp.getWindow();
       // Cursor must move at least 12 pixels before text
       // displayed using IJ.showStatus() is overwritten.
       if ((sx - sx2) * (sx - sx2) + (sy - sy2) * (sy - sy2) > 144) showCursorStatus = true;
       if (win != null && showCursorStatus) win.mouseMoved(ox, oy);
     } else IJ.showStatus("");
   }
 }
Esempio n. 7
0
 public void mouseExited(MouseEvent e) {
   // autoScroll(e);
   ImageWindow win = imp.getWindow();
   if (win != null) setCursor(defaultCursor);
   IJ.showStatus("");
   mouseExited = true;
 }
Esempio n. 8
0
 protected void moveHandle(int sx, int sy) {
   if (clipboard != null) return;
   int ox = ic.offScreenX(sx);
   int oy = ic.offScreenY(sy);
   if (xpf != null) {
     double offset = getOffset(-0.5);
     xpf[activeHandle] = (float) (ic.offScreenXD(sx) - x + offset);
     ypf[activeHandle] = (float) (ic.offScreenYD(sy) - y + offset);
   } else {
     xp[activeHandle] = ox - x;
     yp[activeHandle] = oy - y;
   }
   if (xSpline != null) {
     fitSpline(splinePoints);
     updateClipRect();
     imp.draw(clipX, clipY, clipWidth, clipHeight);
     oldX = x;
     oldY = y;
     oldWidth = width;
     oldHeight = height;
   } else {
     resetBoundingRect();
     if (type == POINT && width == 0 && height == 0) {
       width = 1;
       height = 1;
     }
     updateClipRectAndDraw();
   }
   String angle = type == ANGLE ? getAngleAsString() : "";
   IJ.showStatus(imp.getLocationAsString(ox, oy) + angle);
 }
Esempio n. 9
0
 void handleMouseMove(int sx, int sy) {
   // Do rubber banding
   int tool = Toolbar.getToolId();
   if (!(tool == Toolbar.POLYGON || tool == Toolbar.POLYLINE || tool == Toolbar.ANGLE)) {
     imp.deleteRoi();
     imp.draw();
     return;
   }
   drawRubberBand(sx, sy);
   degrees = Double.NaN;
   double len = -1;
   if (nPoints > 1) {
     double x1, y1, x2, y2;
     if (xpf != null) {
       x1 = xpf[nPoints - 2];
       y1 = ypf[nPoints - 2];
       x2 = xpf[nPoints - 1];
       y2 = ypf[nPoints - 1];
     } else {
       x1 = xp[nPoints - 2];
       y1 = yp[nPoints - 2];
       x2 = xp[nPoints - 1];
       y2 = yp[nPoints - 1];
     }
     degrees =
         getAngle(
             (int) Math.round(x1),
             (int) Math.round(y1),
             (int) Math.round(x2),
             (int) Math.round(y2));
     if (tool != Toolbar.ANGLE) {
       Calibration cal = imp.getCalibration();
       double pw = cal.pixelWidth, ph = cal.pixelHeight;
       if (IJ.altKeyDown()) {
         pw = 1.0;
         ph = 1.0;
       }
       len = Math.sqrt((x2 - x1) * pw * (x2 - x1) * pw + (y2 - y1) * ph * (y2 - y1) * ph);
     }
   }
   if (tool == Toolbar.ANGLE) {
     if (nPoints == 2) angle1 = degrees;
     else if (nPoints == 3) {
       double angle2 = getAngle(xp[1], yp[1], xp[2], yp[2]);
       degrees = Math.abs(180 - Math.abs(angle1 - angle2));
       if (degrees > 180.0) degrees = 360.0 - degrees;
     }
   }
   String length = len != -1 ? ", length=" + IJ.d2s(len) : "";
   double degrees2 =
       tool == Toolbar.ANGLE && nPoints == 3 && Prefs.reflexAngle ? 360.0 - degrees : degrees;
   String angle = !Double.isNaN(degrees) ? ", angle=" + IJ.d2s(degrees2) : "";
   int ox = ic != null ? ic.offScreenX(sx) : sx;
   int oy = ic != null ? ic.offScreenY(sy) : sy;
   IJ.showStatus(imp.getLocationAsString(ox, oy) + length + angle);
 }
Esempio n. 10
0
 private boolean checkImage() {
   imp = WindowManager.getCurrentImage();
   if (imp == null) {
     IJ.beep();
     IJ.showStatus("No image");
     return false;
   }
   ip = setup(imp);
   if (ip == null) return false;
   return true;
 }
Esempio n. 11
0
 void enlargeCanvas() {
   imp.unlock();
   if (imp.getStackSize() == 1) Undo.setup(Undo.COMPOUND_FILTER, imp);
   IJ.run("Select All");
   IJ.run("Rotate...", "angle=" + angle);
   Roi roi = imp.getRoi();
   Rectangle r = roi.getBounds();
   if (r.width < imp.getWidth()) r.width = imp.getWidth();
   if (r.height < imp.getHeight()) r.height = imp.getHeight();
   IJ.showStatus("Rotate: Enlarging...");
   IJ.run(
       "Canvas Size...",
       "width="
           + r.width
           + " height="
           + r.height
           + " position=Center "
           + (fillWithBackground ? "" : "zero"));
   IJ.showStatus("Rotating...");
 }
Esempio n. 12
0
  /** Performs actual projection using specified method. */
  public void doProjection() {
    if (imp == null) return;
    sliceCount = 0;
    if (method < AVG_METHOD || method > MEDIAN_METHOD) method = AVG_METHOD;
    for (int slice = startSlice; slice <= stopSlice; slice += increment) sliceCount++;
    if (method == MEDIAN_METHOD) {
      projImage = doMedianProjection();
      return;
    }

    // Create new float processor for projected pixels.
    FloatProcessor fp = new FloatProcessor(imp.getWidth(), imp.getHeight());
    ImageStack stack = imp.getStack();
    RayFunction rayFunc = getRayFunction(method, fp);
    if (IJ.debugMode == true) {
      IJ.log("\nProjecting stack from: " + startSlice + " to: " + stopSlice);
    }

    // Determine type of input image. Explicit determination of
    // processor type is required for subsequent pixel
    // manipulation.  This approach is more efficient than the
    // more general use of ImageProcessor's getPixelValue and
    // putPixel methods.
    int ptype;
    if (stack.getProcessor(1) instanceof ByteProcessor) ptype = BYTE_TYPE;
    else if (stack.getProcessor(1) instanceof ShortProcessor) ptype = SHORT_TYPE;
    else if (stack.getProcessor(1) instanceof FloatProcessor) ptype = FLOAT_TYPE;
    else {
      IJ.error("Z Project", "Non-RGB stack required");
      return;
    }

    // Do the projection.
    for (int n = startSlice; n <= stopSlice; n += increment) {
      IJ.showStatus("ZProjection " + color + ": " + n + "/" + stopSlice);
      IJ.showProgress(n - startSlice, stopSlice - startSlice);
      projectSlice(stack.getPixels(n), rayFunc, ptype);
    }

    // Finish up projection.
    if (method == SUM_METHOD) {
      fp.resetMinAndMax();
      projImage = new ImagePlus(makeTitle(), fp);
    } else if (method == SD_METHOD) {
      rayFunc.postProcess();
      fp.resetMinAndMax();
      projImage = new ImagePlus(makeTitle(), fp);
    } else {
      rayFunc.postProcess();
      projImage = makeOutputImage(imp, fp, ptype);
    }

    if (projImage == null) IJ.error("Z Project", "Error computing projection.");
  }
Esempio n. 13
0
 void doIterations(ImageProcessor ip, String mode) {
   if (escapePressed) return;
   if (!previewing && iterations > 1) IJ.showStatus(arg + "... press ESC to cancel");
   for (int i = 0; i < iterations; i++) {
     if (Thread.currentThread().isInterrupted()) return;
     if (IJ.escapePressed()) {
       escapePressed = true;
       ip.reset();
       return;
     }
     if (mode.equals("erode")) ((ByteProcessor) ip).erode(count, background);
     else ((ByteProcessor) ip).dilate(count, background);
   }
 }
Esempio n. 14
0
    public void actionPerformed(ActionEvent e) {
      Button b = (Button) e.getSource();
      if (b == null) return;

      boolean imageThere = checkImage();

      if (imageThere) {
        if (b == originalB) {
          reset(imp, ip);
          filteredB.setEnabled(true);
        } else if (b == filteredB) {
          apply(imp, ip);
        } else if (b == sampleB) {
          reset(imp, ip);
          sample();
          apply(imp, ip);
        } else if (b == stackB) {
          applyStack();
        } else if (b == helpB) {
          IJ.showMessage(
              "Help",
              "Threshold Colour  v1.0\n \n"
                  + "Modification of Bob Dougherty's BandPass2 plugin by G.Landini to\n"
                  + "threshold 24 bit RGB images based on Hue, Saturation and Brightness\n"
                  + "or Red, Green and Blue components.\n \n"
                  + "Pass: Band-pass filter (anything within range is displayed).\n \n"
                  + "Stop: Band-reject filter (anything within range is NOT displayed).\n \n"
                  + "Original: Shows the original image and updates the buffer when\n"
                  + " switching to another image.\n \n"
                  + "Filtered: Shows the filtered image.\n \n"
                  + "Stack: Processes the rest of the slices in the stack (if any)\n"
                  + " using the current settings.\n \n"
                  + "Threshold: Shows the object/background in the foreground and\n"
                  + " background colours selected in the ImageJ toolbar.\n \n"
                  + "Invert: Swaps the fore/background colours.\n \n"
                  + "Sample: (experimental) Sets the ranges of the filters based on the\n"
                  + " pixel value componentd in a rectangular, user-defined, ROI.\n \n"
                  + "HSB RGB: Selects HSB or RGB space and resets all the filters.\n \n"
                  + "Note that the \'thresholded\' image is RGB, not 8 bit grey.");
        }
        updatePlot();
        updateLabels();
        imp.updateAndDraw();
      } else {
        IJ.beep();
        IJ.showStatus("No Image");
      }
      notify();
    }
Esempio n. 15
0
 void setStackDisplayRange(ImagePlus imp) {
   ImageStack stack = imp.getStack();
   double min = Double.MAX_VALUE;
   double max = -Double.MAX_VALUE;
   int n = stack.getSize();
   for (int i = 1; i <= n; i++) {
     if (!silentMode) IJ.showStatus("Calculating stack min and max: " + i + "/" + n);
     ImageProcessor ip = stack.getProcessor(i);
     ip.resetMinAndMax();
     if (ip.getMin() < min) min = ip.getMin();
     if (ip.getMax() > max) max = ip.getMax();
   }
   imp.getProcessor().setMinAndMax(min, max);
   imp.updateAndDraw();
 }
Esempio n. 16
0
 /** Opens a stack of images. */
 ImagePlus openStack(ColorModel cm, boolean show) {
   ImageStack stack = new ImageStack(fi.width, fi.height, cm);
   long skip = fi.getOffset();
   Object pixels;
   try {
     ImageReader reader = new ImageReader(fi);
     InputStream is = createInputStream(fi);
     if (is == null) return null;
     IJ.resetEscape();
     for (int i = 1; i <= fi.nImages; i++) {
       if (!silentMode) IJ.showStatus("Reading: " + i + "/" + fi.nImages);
       if (IJ.escapePressed()) {
         IJ.beep();
         IJ.showProgress(1.0);
         silentMode = false;
         return null;
       }
       pixels = reader.readPixels(is, skip);
       if (pixels == null) break;
       stack.addSlice(null, pixels);
       skip = fi.gapBetweenImages;
       if (!silentMode) IJ.showProgress(i, fi.nImages);
     }
     is.close();
   } catch (Exception e) {
     IJ.log("" + e);
   } catch (OutOfMemoryError e) {
     IJ.outOfMemory(fi.fileName);
     stack.trim();
   }
   if (!silentMode) IJ.showProgress(1.0);
   if (stack.getSize() == 0) return null;
   if (fi.sliceLabels != null && fi.sliceLabels.length <= stack.getSize()) {
     for (int i = 0; i < fi.sliceLabels.length; i++) stack.setSliceLabel(fi.sliceLabels[i], i + 1);
   }
   ImagePlus imp = new ImagePlus(fi.fileName, stack);
   if (fi.info != null) imp.setProperty("Info", fi.info);
   if (show) imp.show();
   imp.setFileInfo(fi);
   setCalibration(imp);
   ImageProcessor ip = imp.getProcessor();
   if (ip.getMin() == ip.getMax()) // find stack min and max if first slice is blank
   setStackDisplayRange(imp);
   if (!silentMode) IJ.showProgress(1.0);
   silentMode = false;
   return imp;
 }
Esempio n. 17
0
 void createNewStack(ImagePlus imp, ImageProcessor ip) {
   int nSlices = imp.getStackSize();
   int w = imp.getWidth(), h = imp.getHeight();
   ImagePlus imp2 = imp.createImagePlus();
   Rectangle r = ip.getRoi();
   boolean crop = r.width != imp.getWidth() || r.height != imp.getHeight();
   ImageStack stack1 = imp.getStack();
   ImageStack stack2 = new ImageStack(newWidth, newHeight);
   ImageProcessor ip1, ip2;
   int method = interpolationMethod;
   if (w == 1 || h == 1) method = ImageProcessor.NONE;
   for (int i = 1; i <= nSlices; i++) {
     IJ.showStatus("Scale: " + i + "/" + nSlices);
     ip1 = stack1.getProcessor(i);
     String label = stack1.getSliceLabel(i);
     if (crop) {
       ip1.setRoi(r);
       ip1 = ip1.crop();
     }
     ip1.setInterpolationMethod(method);
     ip2 = ip1.resize(newWidth, newHeight, averageWhenDownsizing);
     if (ip2 != null) stack2.addSlice(label, ip2);
     IJ.showProgress(i, nSlices);
   }
   imp2.setStack(title, stack2);
   Calibration cal = imp2.getCalibration();
   if (cal.scaled()) {
     cal.pixelWidth *= 1.0 / xscale;
     cal.pixelHeight *= 1.0 / yscale;
   }
   IJ.showProgress(1.0);
   int[] dim = imp.getDimensions();
   imp2.setDimensions(dim[2], dim[3], dim[4]);
   if (imp.isComposite()) {
     imp2 = new CompositeImage(imp2, ((CompositeImage) imp).getMode());
     ((CompositeImage) imp2).copyLuts(imp);
   }
   if (imp.isHyperStack()) imp2.setOpenAsHyperStack(true);
   if (newDepth > 0 && newDepth != oldDepth)
     imp2 = (new Resizer()).zScale(imp2, newDepth, interpolationMethod);
   if (imp2 != null) {
     imp2.show();
     imp2.changes = true;
   }
 }
Esempio n. 18
0
 void applyStack() {
   // int minKeepH = minHue, maxKeepH = maxHue; //GL not needed?
   // int minKeepS = minSat, maxKeepS = maxSat;
   // int minKeepB = minBri, maxKeepB = maxBri;
   for (int i = 1; i <= numSlices; i++) {
     imp.setSlice(i);
     if (!checkImage()) {
       IJ.beep();
       IJ.showStatus("No Image");
       return;
     }
     //	minHue = minKeepH;
     //	maxHue = maxKeepH;
     //	minSat = minKeepS;
     //	maxSat = maxKeepS;
     //	minBri = minKeepB;
     //	maxBri = maxKeepB;
     apply(imp, ip);
   }
 }
Esempio n. 19
0
 protected void setDrawingColor(int ox, int oy, boolean setBackground) {
   // IJ.log("setDrawingColor: "+setBackground+this);
   int type = imp.getType();
   int[] v = imp.getPixel(ox, oy);
   switch (type) {
     case ImagePlus.GRAY8:
       {
         if (setBackground) setBackgroundColor(getColor(v[0]));
         else setForegroundColor(getColor(v[0]));
         break;
       }
     case ImagePlus.GRAY16:
     case ImagePlus.GRAY32:
       {
         double min = imp.getProcessor().getMin();
         double max = imp.getProcessor().getMax();
         double value = (type == ImagePlus.GRAY32) ? Float.intBitsToFloat(v[0]) : v[0];
         int index = (int) (255.0 * ((value - min) / (max - min)));
         if (index < 0) index = 0;
         if (index > 255) index = 255;
         if (setBackground) setBackgroundColor(getColor(index));
         else setForegroundColor(getColor(index));
         break;
       }
     case ImagePlus.COLOR_RGB:
     case ImagePlus.COLOR_256:
       {
         Color c = new Color(v[0], v[1], v[2]);
         if (setBackground) setBackgroundColor(c);
         else setForegroundColor(c);
         break;
       }
   }
   Color c;
   if (setBackground) c = Toolbar.getBackgroundColor();
   else {
     c = Toolbar.getForegroundColor();
     imp.setColor(c);
   }
   IJ.showStatus("(" + c.getRed() + ", " + c.getGreen() + ", " + c.getBlue() + ")");
 }
Esempio n. 20
0
 void createNewStack(ImagePlus imp, ImageProcessor ip) {
   Rectangle r = ip.getRoi();
   boolean crop = r.width != imp.getWidth() || r.height != imp.getHeight();
   int nSlices = imp.getStackSize();
   ImageStack stack1 = imp.getStack();
   ImageStack stack2 = new ImageStack(newWidth, newHeight);
   ImageProcessor ip1, ip2;
   boolean interp = interpolate;
   if (imp.getWidth() == 1 || imp.getHeight() == 1) interp = false;
   for (int i = 1; i <= nSlices; i++) {
     IJ.showStatus("Scale: " + i + "/" + nSlices);
     ip1 = stack1.getProcessor(i);
     String label = stack1.getSliceLabel(i);
     if (crop) {
       ip1.setRoi(r);
       ip1 = ip1.crop();
     }
     ip1.setInterpolate(interp);
     ip2 = ip1.resize(newWidth, newHeight);
     if (ip2 != null) stack2.addSlice(label, ip2);
     IJ.showProgress(i, nSlices);
   }
   ImagePlus imp2 = imp.createImagePlus();
   imp2.setStack(title, stack2);
   Calibration cal = imp2.getCalibration();
   if (cal.scaled()) {
     cal.pixelWidth *= 1.0 / xscale;
     cal.pixelHeight *= 1.0 / yscale;
   }
   int[] dim = imp.getDimensions();
   imp2.setDimensions(dim[2], dim[3], dim[4]);
   IJ.showProgress(1.0);
   if (imp.isComposite()) {
     imp2 = new CompositeImage(imp2, 0);
     ((CompositeImage) imp2).copyLuts(imp);
   }
   if (imp.isHyperStack()) imp2.setOpenAsHyperStack(true);
   imp2.show();
   imp2.changes = true;
 }
Esempio n. 21
0
  public boolean dialogItemChanged(GenericDialog gd, AWTEvent e) {
    int width = imp.getWidth();
    int height = imp.getHeight();
    type = gd.getNextChoice();
    areaPerPoint = gd.getNextNumber();
    color = gd.getNextChoice();
    randomOffset = gd.getNextBoolean();

    double minArea = (width * height) / 50000.0;
    if (type.equals(types[1]) && minArea < 144.0) minArea = 144.0;
    else if (minArea < 16) minArea = 16.0;
    if (areaPerPoint / (pixelWidth * pixelHeight) < minArea) {
      String err = "\"Area per Point\" too small";
      if (gd.wasOKed()) IJ.error("Grid", err);
      else IJ.showStatus(err);
      return true;
    }
    double tileSize = Math.sqrt(areaPerPoint);
    tileWidth = tileSize / pixelWidth;
    tileHeight = tileSize / pixelHeight;
    if (randomOffset) {
      xstart = (int) (random.nextDouble() * tileWidth);
      ystart = (int) (random.nextDouble() * tileHeight);
    } else {
      xstart = (int) (tileWidth / 2.0 + 0.5);
      ystart = (int) (tileHeight / 2.0 + 0.5);
    }
    linesV = (int) ((width - xstart) / tileWidth) + 1;
    linesH = (int) ((height - ystart) / tileHeight) + 1;
    if (gd.invalidNumber()) return true;
    if (type.equals(types[0])) drawLines();
    else if (type.equals(types[1])) drawCrosses();
    else if (type.equals(types[2])) drawPoints();
    else showGrid(null);
    return true;
  }
Esempio n. 22
0
 ImagePlus doMedianProjection() {
   IJ.showStatus("Calculating median...");
   ImageStack stack = imp.getStack();
   ImageProcessor[] slices = new ImageProcessor[sliceCount];
   int index = 0;
   for (int slice = startSlice; slice <= stopSlice; slice += increment)
     slices[index++] = stack.getProcessor(slice);
   ImageProcessor ip2 = slices[0].duplicate();
   ip2 = ip2.convertToFloat();
   float[] values = new float[sliceCount];
   int width = ip2.getWidth();
   int height = ip2.getHeight();
   int inc = Math.max(height / 30, 1);
   for (int y = 0; y < height; y++) {
     if (y % inc == 0) IJ.showProgress(y, height - 1);
     for (int x = 0; x < width; x++) {
       for (int i = 0; i < sliceCount; i++) values[i] = slices[i].getPixelValue(x, y);
       ip2.putPixelValue(x, y, median(values));
     }
   }
   if (imp.getBitDepth() == 8) ip2 = ip2.convertToByte(false);
   IJ.showProgress(1, 1);
   return new ImagePlus(makeTitle(), ip2);
 }
Esempio n. 23
0
  private void fitglobal() {
    int nparams = 11;
    int nsel = 0;
    for (int i = 0; i < ncurves; i++) {
      if (include[i]) {
        nsel++;
      }
    }
    double[][] params = new double[nsel][nparams];
    String[][] tempformulas = new String[nsel][nparams];
    double[][][] constraints = new double[2][nsel][nparams];
    int[][] vflmatrix = new int[nsel][nparams];

    int counter = 0;
    for (int i = 0; i < ncurves; i++) {
      if (include[i]) {
        for (int j = 0; j < nparams; j++) {
          params[counter][j] = globalparams[i][j];
          tempformulas[counter][j] = globalformulas[i][j];
          constraints[0][counter][j] = globalconstraints[0][i][j];
          constraints[1][counter][j] = globalconstraints[1][i][j];
          vflmatrix[counter][j] = globalvflmatrix[i][j];
        }
        counter++;
      }
      for (int j = 0; j < nparams; j++) {
        undoparams[i][j] = globalparams[i][j];
        undoformulas[i][j] = globalformulas[i][j];
        undovflmatrix[i][j] = globalvflmatrix[i][j];
      }
      for (int j = 0; j < xpts; j++) {
        for (int k = 0; k < ypts; k++) {
          undofit[i][j][k] = fit[i][j][k];
        }
      }
      undoc2[i] = c2[i];
    }
    undoglobalc2 = globalc2;
    if (showglobalfitdialog(params, tempformulas, vflmatrix)) {
      counter = 0;
      for (int i = 0; i < ncurves; i++) {
        if (include[i]) {
          for (int j = 0; j < nparams; j++) {
            globalparams[i][j] = params[counter][j];
            globalformulas[i][j] = tempformulas[counter][j];
            globalvflmatrix[i][j] = vflmatrix[counter][j];
          }
          counter++;
        }
      }
      double[] stats = new double[2];
      float[][] tempdata = new float[nsel][xpts * ypts];
      float[][] tempweights = new float[nsel][xpts * ypts];
      counter = 0;
      for (int i = 0; i < ncurves; i++) {
        if (include[i]) {
          for (int j = 0; j < xpts; j++) {
            for (int k = 0; k < ypts; k++) {
              tempdata[counter][j + k * xpts] = (float) ((double) pch[i][j][k] / (double) nmeas[i]);
              tempweights[counter][j + k * xpts] = weights[i][j][k];
            }
          }
          counter++;
        }
      }
      int tempmaxiter = globalfitclass.maxiter;
      if (checkc2) {
        globalfitclass.changemaxiter(0);
      }
      double[] tempc2vals = new double[nsel];
      IJ.showStatus("Fitting Globally");
      float[][] tempfit =
          globalfitclass.fitdata(
              params,
              vflmatrix,
              tempformulas,
              paramsnames,
              constraints,
              tempdata,
              tempweights,
              stats,
              tempc2vals,
              false);
      IJ.showStatus("Fit Complete");
      globalfitclass.changemaxiter(tempmaxiter);
      globalc2 = stats[1];
      globalc2label.setText("Global chi^2 = " + (float) globalc2);
      counter = 0;
      for (int i = 0; i < ncurves; i++) {
        if (include[i]) {
          for (int j = 0; j < xpts; j++) {
            for (int k = 0; k < ypts; k++) {
              fit[i][j][k] = tempfit[counter][j + xpts * k] * (float) nmeas[i];
            }
          }
          if (i == dispcurve) {
            pwfit.updateSeries(fit[dispcurve], 1, true);
          }
          for (int j = 0; j < nparams; j++) {
            globalparams[i][j] = params[counter][j];
          }
          c2[i] = tempc2vals[counter];
          c2array[i].setText("" + (float) c2[i]);
          counter++;
        }
      }
      float[] temp = pwfit.getLimits();
      temp[4] = 1.0f;
      pwfit.setLimits(temp);
    }
  }
Esempio n. 24
0
 public void showresults(String results) {
   IJ.showStatus(results);
   IJ.log(results);
 }
Esempio n. 25
0
 public void mousePressed(MouseEvent e) {
   Undo.reset();
   if (!Prefs.noClickToGC) System.gc();
   IJ.showStatus(version() + IJ.freeMemory());
   if (IJ.debugMode) IJ.log("Windows: " + WindowManager.getWindowCount());
 }
Esempio n. 26
0
  /**
   * If 'applet' is not null, creates a new ImageJ frame that runs as an applet. If 'mode' is
   * ImageJ.EMBEDDED and 'applet is null, creates an embedded (non-standalone) version of ImageJ.
   */
  public ImageJ(java.applet.Applet applet, int mode) {
    super("ImageJ");
    embedded = applet == null && (mode == EMBEDDED || mode == NO_SHOW);
    this.applet = applet;
    String err1 = Prefs.load(this, applet);
    if (IJ.isLinux()) {
      backgroundColor = new Color(240, 240, 240);
      setBackground(backgroundColor);
    }
    Menus m = new Menus(this, applet);
    String err2 = m.addMenuBar();
    m.installPopupMenu(this);
    setLayout(new GridLayout(2, 1));

    // Tool bar
    toolbar = new Toolbar();
    toolbar.addKeyListener(this);
    add(toolbar);

    // Status bar
    statusBar = new Panel();
    statusBar.setLayout(new BorderLayout());
    statusBar.setForeground(Color.black);
    statusBar.setBackground(backgroundColor);
    statusLine = new Label();
    statusLine.setFont(SansSerif12);
    statusLine.addKeyListener(this);
    statusLine.addMouseListener(this);
    statusBar.add("Center", statusLine);
    progressBar = new ProgressBar(120, 20);
    progressBar.addKeyListener(this);
    progressBar.addMouseListener(this);
    statusBar.add("East", progressBar);
    statusBar.setSize(toolbar.getPreferredSize());
    add(statusBar);

    IJ.init(this, applet);
    addKeyListener(this);
    addWindowListener(this);
    setFocusTraversalKeysEnabled(false);

    Point loc = getPreferredLocation();
    Dimension tbSize = toolbar.getPreferredSize();
    int ijWidth = tbSize.width + 10;
    int ijHeight = 100;
    setCursor(Cursor.getDefaultCursor()); // work-around for JDK 1.1.8 bug
    if (mode != NO_SHOW) {
      if (IJ.isWindows())
        try {
          setIcon();
        } catch (Exception e) {
        }
      setBounds(loc.x, loc.y, ijWidth, ijHeight); // needed for pack to work
      setLocation(loc.x, loc.y);
      pack();
      setResizable(!(IJ.isMacintosh() || IJ.isWindows())); // make resizable on Linux
      show();
    }
    if (err1 != null) IJ.error(err1);
    if (err2 != null) {
      IJ.error(err2);
      IJ.runPlugIn("ij.plugin.ClassChecker", "");
    }
    m.installStartupMacroSet();
    if (IJ.isMacintosh() && applet == null) {
      Object qh = null;
      qh = IJ.runPlugIn("MacAdapter", "");
      if (qh == null) IJ.runPlugIn("QuitHandler", "");
    }
    if (applet == null) IJ.runPlugIn("ij.plugin.DragAndDrop", "");
    String str = m.getMacroCount() == 1 ? " macro" : " macros";
    IJ.showStatus(version() + m.getPluginCount() + " commands; " + m.getMacroCount() + str);
    // if (applet==null && !embedded && Prefs.runSocketListener)
    //	new SocketListener();
    configureProxy();
    if (applet == null) loadCursors();
  }
Esempio n. 27
0
	public void run(String arg) {

  int[] wList = WindowManager.getIDList();
        if (wList==null) {
            IJ.error("No images are open.");
            return;
        }
	double kernel=3;
	double kernelsum = 0;
	double kernelvarsum =0;
	double kernalvar = 0;
	double sigmawidth = 2;
	int kernelindex, minpixnumber;
	String[] kernelsize =  { "3�,"5�, "7�, "9�};

	GenericDialog gd = new GenericDialog("Sigma Filter");
	gd.addChoice("Kernel size", kernelsize, kernelsize[0]);
	gd.addNumericField("Sigma width",sigmawidth , 2);
	gd.addNumericField("Minimum number of pixels", 1, 0);

	gd.addCheckbox("Keep source:",true);
	gd.addCheckbox("Do all stack:",true);
	gd.addCheckbox("Modified Lee's FIlter:",true);
	       	
	gd.showDialog();
       	if (gd.wasCanceled()) return ;
	kernelindex =  gd.getNextChoiceIndex();
          	sigmawidth = gd.getNextNumber();
          	minpixnumber = ((int)gd.getNextNumber());
          	boolean keep = gd.getNextBoolean();
	boolean doallstack = gd.getNextBoolean();
	boolean modified = gd.getNextBoolean();
	if (kernelindex==0) kernel = 3;
	if (kernelindex==1) kernel = 5;
	if (kernelindex==2) kernel = 7;
	if (kernelindex==3) kernel = 9;
    	long start = System.currentTimeMillis();
	
if (minpixnumber> (kernel*kernel)){
	      IJ.showMessage("Sigma filter", "There must be more pixels in the kernel than+\n" + "the minimum number to be included");
            return;
        }
	double v, midintensity;
	int   x, y, ix, iy;
	double sum = 0;
	double backupsum =0;
	int count = 0;
	int n = 0;
	if (keep) {IJ.run("Select All"); IJ.run("Duplicate...", "title='Sigma filtered' duplicate");}

	int radius = (int)(kernel-1)/2;
	ImagePlus imp = WindowManager.getCurrentImage();
	ImageStack stack1 = imp.getStack();
	int width = imp.getWidth();
	int height = imp.getHeight();
	int nslices = stack1.getSize();
	int cslice = imp.getCurrentSlice();
	double status = width*height*nslices;
	
	ImageProcessor  ip = imp.getProcessor();
	int sstart = 1;
	if (!doallstack) {sstart = cslice; nslices=sstart;status = status/nslices;};

 for (int i=sstart; i<=nslices; i++) {
                imp.setSlice(i);
                    
for (x=radius;x<width+radius;x++)	{
		for (y=radius;y<height+radius;y++)	{
			
			midintensity = ip.getPixelValue(x,y);
			count = 0;
			sum = 0;
			kernelsum =0;
			kernalvar =0;
			kernelvarsum =0;
			backupsum = 0;

		//calculate mean of kernel value
			for (ix=0;ix<kernel;ix++)	{
					for (iy=0;iy<kernel;iy++)	{
							v = ip.getPixelValue(x+ix-radius,y+iy-radius);
							kernelsum = kernelsum+v;
								}
						}
			double sigmacalcmean = (kernelsum/(kernel*kernel));

		//calculate variance of kernel
			for (ix=0;ix<kernel;ix++)	{
					for (iy=0;iy<kernel;iy++)	{
							v = ip.getPixelValue(x+ix-radius,y+iy-radius);
							kernalvar = (v-sigmacalcmean)*(v-sigmacalcmean);
							kernelvarsum = kernelvarsum + kernalvar;
								}
						}
			//double variance = kernelvarsum/kernel;
			double sigmacalcvar = kernelvarsum/((kernel*kernel)-1);

			//calcuate sigma range = sqrt(variance/(mean^2)) � sigmawidth
			double sigmarange  = sigmawidth*(Math.sqrt((sigmacalcvar) /(sigmacalcmean*sigmacalcmean)));
			//calulate sigma top value and bottom value
			double sigmatop = midintensity*(1+sigmarange);
			double sigmabottom = midintensity*(1-sigmarange);
			//calculate mean of values that differ are in sigma range.
			for (ix=0;ix<kernel;ix++)	{
					for (iy=0;iy<kernel;iy++)	{
							v = ip.getPixelValue(x+ix-radius,y+iy-radius);
							if ((v>=sigmabottom)&&(v<=sigmatop)){
								sum = sum+v;
								count = count+1;   }
								backupsum = v+ backupsum;
										}		
						}
//if there are too few pixels in the kernal that are within sigma range, the 
//mean of the entire kernal is taken. My modification of Lee's filter is to exclude the central value 
//from the calculation of the mean as I assume it to be spuriously high or low 
			if (!(count>(minpixnumber)))
				{sum = (backupsum-midintensity);
				count = (int)((kernel*kernel)-1);
				if (!modified)
					{sum = (backupsum);
					count  = (int)(kernel*kernel);}
				}
			
			double val =  (sum/count);
			ip.putPixelValue(x,y, val);
			n = n+1;
	double percentage = (((double)n/status)*100);
			 IJ.showStatus(IJ.d2s(percentage,0) +"% done");		
			
}

	//		IJ.showProgress(i, status);
					}}
			imp.updateAndDraw();
 			IJ.showStatus(IJ.d2s((System.currentTimeMillis()-start)/1000.0, 2)+" seconds");        }      
 void install() {
   subMenus.clear();
   if (text != null) {
     Tokenizer tok = new Tokenizer();
     pgm = tok.tokenize(text);
   }
   if (macrosMenu != null) IJ.showStatus("");
   int[] code = pgm.getCode();
   Symbol[] symbolTable = pgm.getSymbolTable();
   int count = 0, token, nextToken, address;
   String name;
   Symbol symbol;
   shortcutsInUse = null;
   inUseCount = 0;
   nShortcuts = 0;
   toolCount = 0;
   macroStarts = new int[MAX_MACROS];
   macroNames = new String[MAX_MACROS];
   boolean isPluginsMacrosMenu = false;
   if (macrosMenu != null) {
     int itemCount = macrosMenu.getItemCount();
     isPluginsMacrosMenu = macrosMenu == Menus.getMacrosMenu();
     int baseCount = isPluginsMacrosMenu ? MACROS_MENU_COMMANDS : Editor.MACROS_MENU_ITEMS;
     if (itemCount > baseCount) {
       for (int i = itemCount - 1; i >= baseCount; i--) macrosMenu.remove(i);
     }
   }
   if (pgm.hasVars() && pgm.macroCount() > 0 && pgm.getGlobals() == null)
     new Interpreter().saveGlobals(pgm);
   ArrayList tools = new ArrayList();
   for (int i = 0; i < code.length; i++) {
     token = code[i] & TOK_MASK;
     if (token == MACRO) {
       nextToken = code[i + 1] & TOK_MASK;
       if (nextToken == STRING_CONSTANT) {
         if (count == MAX_MACROS) {
           if (isPluginsMacrosMenu)
             IJ.error("Macro Installer", "Macro sets are limited to " + MAX_MACROS + " macros.");
           break;
         }
         address = code[i + 1] >> TOK_SHIFT;
         symbol = symbolTable[address];
         name = symbol.str;
         macroStarts[count] = i + 2;
         macroNames[count] = name;
         if (name.indexOf('-') != -1
             && (name.indexOf("Tool") != -1 || name.indexOf("tool") != -1)) {
           tools.add(name);
           toolCount++;
         } else if (name.startsWith("AutoRun")) {
           if (autoRunCount == 0 && !openingStartupMacrosInEditor) {
             new MacroRunner(pgm, macroStarts[count], name, (String) null);
             if (name.equals("AutoRunAndHide")) autoRunAndHideCount++;
           }
           autoRunCount++;
           count--;
         } else if (name.equals("Popup Menu")) installPopupMenu(name, pgm);
         else if (!name.endsWith("Tool Selected")) {
           if (macrosMenu != null) {
             addShortcut(name);
             int pos = name.indexOf(">");
             boolean inSubMenu = name.startsWith("<") && (pos > 1);
             if (inSubMenu) {
               Menu parent = macrosMenu;
               Menu subMenu = null;
               String parentStr = name.substring(1, pos).trim();
               String childStr = name.substring(pos + 1).trim();
               MenuItem mnuItem = new MenuItem();
               mnuItem.setActionCommand(name);
               mnuItem.setLabel(childStr);
               for (int jj = 0; jj < subMenus.size(); jj++) {
                 String aName = subMenus.get(jj).getName();
                 if (aName.equals(parentStr)) subMenu = subMenus.get(jj);
               }
               if (subMenu == null) {
                 subMenu = new Menu(parentStr);
                 subMenu.setName(parentStr);
                 subMenu.addActionListener(this);
                 subMenus.add(subMenu);
                 parent.add(subMenu);
               }
               subMenu.add(mnuItem);
             } else macrosMenu.add(new MenuItem(name));
           }
         }
         // IJ.log(count+" "+name+" "+macroStarts[count]);
         count++;
       }
     } else if (token == EOF) break;
   }
   nMacros = count;
   if (toolCount > 0 && (isPluginsMacrosMenu || macrosMenu == null) && installTools) {
     Toolbar tb = Toolbar.getInstance();
     if (toolCount == 1) tb.addMacroTool((String) tools.get(0), this);
     else {
       for (int i = 0; i < tools.size(); i++) {
         String toolName = (String) tools.get(i);
         if (toolName.startsWith("Abort Macro or Plugin") && toolCount > 6)
           toolName = "Unused " + toolName;
         tb.addMacroTool(toolName, this, i);
       }
     }
     if (toolCount > 1 && Toolbar.getToolId() >= Toolbar.CUSTOM1) tb.setTool(Toolbar.RECTANGLE);
     tb.repaint();
   }
   if (macrosMenu != null) this.instance = this;
   if (shortcutsInUse != null && text != null)
     IJ.showMessage(
         "Install Macros",
         (inUseCount == 1 ? "This keyboard shortcut is" : "These keyboard shortcuts are")
             + " already in use:"
             + shortcutsInUse);
   if (nMacros == 0 && fileName != null) {
     if (text == null || text.length() == 0) return;
     int dotIndex = fileName.lastIndexOf('.');
     if (dotIndex > 0) anonymousName = fileName.substring(0, dotIndex);
     else anonymousName = fileName;
     if (macrosMenu != null) macrosMenu.add(new MenuItem(anonymousName));
     macroNames[0] = anonymousName;
     nMacros = 1;
   }
   String word = nMacros == 1 ? " macro" : " macros";
   if (isPluginsMacrosMenu) IJ.showStatus(nMacros + word + " installed");
 }
Esempio n. 29
0
  /** Restores original disk or network version of image. */
  public void revertToSaved(ImagePlus imp) {
    Image img;
    ProgressBar pb = IJ.getInstance().getProgressBar();
    ImageProcessor ip;
    String path = fi.directory + fi.fileName;

    if (fi.fileFormat == fi.GIF_OR_JPG) {
      // restore gif or jpg
      img = Toolkit.getDefaultToolkit().createImage(path);
      imp.setImage(img);
      if (imp.getType() == ImagePlus.COLOR_RGB) Opener.convertGrayJpegTo8Bits(imp);
      return;
    }

    if (fi.fileFormat == fi.DICOM) {
      // restore DICOM
      ImagePlus imp2 = (ImagePlus) IJ.runPlugIn("ij.plugin.DICOM", path);
      if (imp2 != null) imp.setProcessor(null, imp2.getProcessor());
      return;
    }

    if (fi.fileFormat == fi.BMP) {
      // restore BMP
      ImagePlus imp2 = (ImagePlus) IJ.runPlugIn("ij.plugin.BMP_Reader", path);
      if (imp2 != null) imp.setProcessor(null, imp2.getProcessor());
      return;
    }

    if (fi.fileFormat == fi.PGM) {
      // restore PGM
      ImagePlus imp2 = (ImagePlus) IJ.runPlugIn("ij.plugin.PGM_Reader", path);
      if (imp2 != null) imp.setProcessor(null, imp2.getProcessor());
      return;
    }

    if (fi.fileFormat == fi.ZIP_ARCHIVE) {
      // restore ".zip" file
      ImagePlus imp2 = (new Opener()).openZip(path);
      if (imp2 != null) imp.setProcessor(null, imp2.getProcessor());
      return;
    }

    // restore PNG or another image opened using ImageIO
    if (fi.fileFormat == fi.IMAGEIO) {
      ImagePlus imp2 = (new Opener()).openUsingImageIO(path);
      if (imp2 != null) imp.setProcessor(null, imp2.getProcessor());
      return;
    }

    if (fi.nImages > 1) return;

    ColorModel cm;
    if (fi.url == null || fi.url.equals("")) IJ.showStatus("Loading: " + path);
    else IJ.showStatus("Loading: " + fi.url + fi.fileName);
    Object pixels = readPixels(fi);
    if (pixels == null) return;
    cm = createColorModel(fi);
    switch (fi.fileType) {
      case FileInfo.GRAY8:
      case FileInfo.COLOR8:
      case FileInfo.BITMAP:
        ip = new ByteProcessor(width, height, (byte[]) pixels, cm);
        imp.setProcessor(null, ip);
        break;
      case FileInfo.GRAY16_SIGNED:
      case FileInfo.GRAY16_UNSIGNED:
      case FileInfo.GRAY12_UNSIGNED:
        ip = new ShortProcessor(width, height, (short[]) pixels, cm);
        imp.setProcessor(null, ip);
        break;
      case FileInfo.GRAY32_INT:
      case FileInfo.GRAY32_FLOAT:
        ip = new FloatProcessor(width, height, (float[]) pixels, cm);
        imp.setProcessor(null, ip);
        break;
      case FileInfo.RGB:
      case FileInfo.BGR:
      case FileInfo.ARGB:
      case FileInfo.ABGR:
      case FileInfo.RGB_PLANAR:
        img =
            Toolkit.getDefaultToolkit()
                .createImage(new MemoryImageSource(width, height, (int[]) pixels, 0, width));
        imp.setImage(img);
        break;
    }
  }
Esempio n. 30
0
  /**
   * If 'applet' is not null, creates a new ImageJ frame that runs as an applet. If 'mode' is
   * ImageJ.EMBEDDED and 'applet is null, creates an embedded (non-standalone) version of ImageJ.
   */
  public ImageJ(java.applet.Applet applet, int mode) {
    super("ImageJ");
    if ((mode & DEBUG) != 0) IJ.setDebugMode(true);
    mode = mode & 255;
    if (IJ.debugMode) IJ.log("ImageJ starting in debug mode: " + mode);
    embedded = applet == null && (mode == EMBEDDED || mode == NO_SHOW);
    this.applet = applet;
    String err1 = Prefs.load(this, applet);
    setBackground(backgroundColor);
    Menus m = new Menus(this, applet);
    String err2 = m.addMenuBar();
    m.installPopupMenu(this);
    setLayout(new BorderLayout());

    // Tool bar
    toolbar = new Toolbar();
    toolbar.addKeyListener(this);
    add("Center", toolbar);

    // Status bar
    statusBar = new Panel();
    statusBar.setLayout(new BorderLayout());
    statusBar.setForeground(Color.black);
    statusBar.setBackground(backgroundColor);
    statusLine = new JLabel();
    statusLine.setFont(new Font("SansSerif", Font.PLAIN, 13));
    statusLine.addKeyListener(this);
    statusLine.addMouseListener(this);
    statusBar.add("Center", statusLine);
    progressBar = new ProgressBar(120, 20);
    progressBar.addKeyListener(this);
    progressBar.addMouseListener(this);
    statusBar.add("East", progressBar);
    add("South", statusBar);

    IJ.init(this, applet);
    addKeyListener(this);
    addWindowListener(this);
    setFocusTraversalKeysEnabled(false);
    m.installStartupMacroSet(); // add custom tools
    runStartupMacro();

    Point loc = getPreferredLocation();
    Dimension tbSize = toolbar.getPreferredSize();
    setCursor(Cursor.getDefaultCursor()); // work-around for JDK 1.1.8 bug
    if (mode != NO_SHOW) {
      if (IJ.isWindows())
        try {
          setIcon();
        } catch (Exception e) {
        }
      setLocation(loc.x, loc.y);
      setResizable(!IJ.isMacOSX());
      pack();
      setVisible(true);
    }
    if (err1 != null) IJ.error(err1);
    if (err2 != null) {
      IJ.error(err2);
      IJ.runPlugIn("ij.plugin.ClassChecker", "");
    }
    if (IJ.isMacintosh() && applet == null) {
      Object qh = null;
      qh = IJ.runPlugIn("MacAdapter", "");
      if (qh == null) IJ.runPlugIn("QuitHandler", "");
    }
    if (applet == null) IJ.runPlugIn("ij.plugin.DragAndDrop", "");
    String str = m.getMacroCount() == 1 ? " macro" : " macros";
    IJ.showStatus(version() + m.getPluginCount() + " commands; " + m.getMacroCount() + str);
    configureProxy();
    if (applet == null) loadCursors();
  }