Beispiel #1
0
  public void run(String arg) {
    final ExecutorService executorService =
        Cluster.activeCluster()
            ? Cluster.getCluster().getService(1)
            : Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    final ArrayList<Future<ArrayList<Float>>> futures = new ArrayList<Future<ArrayList<Float>>>();

    for (int i = 0; i < 128; ++i) {
      final ArrayList<Float> floats = new ArrayList<Float>();
      final Float f = new Float(i);
      final Integer id = uid.getAndIncrement();

      floats.add(f);
      ifmap.put(id, f);
      fimap.put(f, id);
      ffmap.put(f, f);
      futures.add(executorService.submit(new EqCall(floats)));
    }

    try {
      for (Future<ArrayList<Float>> fu : futures) {
        Float fc = fu.get().get(0);
        // Integer i = fimap.get(fc);
        // Float fo = i == null ? null : ifmap.get(i);
        Float fo = ffmap.get(fc);
        String eqstr = fo == fc ? "they are equal" : "they are unequal";
        IJ.log("Got back float " + fc + " keyed to " + fo + " and " + eqstr);
      }
    } catch (InterruptedException ie) {
      IJ.log("Woops: " + ie);
    } catch (ExecutionException ee) {
      IJ.log("Woops: " + ee);
    }
  }
Beispiel #2
0
 byte[] getJar(String address) {
   // System.out.println("getJar: "+address);
   byte[] data;
   try {
     URL url = new URL(address);
     IJ.showStatus("Connecting to " + IJ.URL);
     URLConnection uc = url.openConnection();
     int len = uc.getContentLength();
     if (IJ.debugMode) IJ.log("Updater (url): " + address + " " + len);
     if (len <= 0) return null;
     String name = address.contains("wsr") ? "daily build (" : "ij.jar (";
     IJ.showStatus("Downloading " + name + IJ.d2s((double) len / 1048576, 1) + "MB)");
     InputStream in = uc.getInputStream();
     data = new byte[len];
     int n = 0;
     while (n < len) {
       int count = in.read(data, n, len - n);
       if (count < 0) throw new EOFException();
       n += count;
       IJ.showProgress(n, len);
     }
     in.close();
   } catch (IOException e) {
     if (IJ.debugMode) IJ.log("" + e);
     return null;
   }
   if (IJ.debugMode) IJ.wait(6000);
   return data;
 }
Beispiel #3
0
  /**
   * Calculate the precision-recall values based on Rand index between some 2D original labels and
   * the corresponding proposed labels. We follow the definition of Rand index as described by
   * William M. Rand \cite{Rand71}.
   *
   * <p>BibTeX:
   *
   * <pre>
   * &#64;article{Rand71,label
   *   author    = {William M. Rand},
   *   title     = {Objective criteria for the evaluation of clustering methods},
   *   journal   = {Journal of the American Statistical Association},
   *   year      = {1971},
   *   volume    = {66},
   *   number    = {336},
   *   pages     = {846--850},
   *   doi       = {10.2307/2284239)
   * }
   * </pre>
   *
   * @param minThreshold minimum threshold value to binarize the input images
   * @param maxThreshold maximum threshold value to binarize the input images
   * @param stepThreshold threshold step value to use during binarization
   * @return Rand index value and derived statistics for each threshold
   */
  public ArrayList<ClassificationStatistics> getRandIndexStats(
      double minThreshold, double maxThreshold, double stepThreshold) {

    if (minThreshold < 0 || minThreshold >= maxThreshold || maxThreshold > 1) {
      IJ.log("Error: unvalid threshold values.");
      return null;
    }

    ArrayList<ClassificationStatistics> cs = new ArrayList<ClassificationStatistics>();

    double bestFscore = 0;
    double bestTh = minThreshold;

    for (double th = minThreshold; th <= maxThreshold; th += stepThreshold) {
      if (verbose)
        IJ.log(
            "  Calculating Rand index statistics for threshold value "
                + String.format("%.3f", th)
                + "...");
      cs.add(getRandIndexStats(th));
      final double fScore = cs.get(cs.size() - 1).fScore;
      if (fScore > bestFscore) {
        bestFscore = fScore;
        bestTh = th;
      }
      if (verbose) IJ.log("    F-score = " + fScore);
    }

    if (verbose)
      IJ.log(" ** Best F-score = " + bestFscore + ", with threshold = " + bestTh + " **\n");

    return cs;
  }
Beispiel #4
0
 public void drop(DropTargetDropEvent dtde) {
   dtde.acceptDrop(DnDConstants.ACTION_COPY);
   DataFlavor[] flavors = null;
   try {
     Transferable t = dtde.getTransferable();
     iterator = null;
     flavors = t.getTransferDataFlavors();
     if (IJ.debugMode) IJ.log("DragAndDrop.drop: " + flavors.length + " flavors");
     for (int i = 0; i < flavors.length; i++) {
       if (IJ.debugMode) IJ.log("  flavor[" + i + "]: " + flavors[i].getMimeType());
       if (flavors[i].isFlavorJavaFileListType()) {
         Object data = t.getTransferData(DataFlavor.javaFileListFlavor);
         iterator = ((List) data).iterator();
         break;
       } else if (flavors[i].isFlavorTextType()) {
         Object ob = t.getTransferData(flavors[i]);
         if (!(ob instanceof String)) continue;
         String s = ob.toString().trim();
         if (IJ.isLinux() && s.length() > 1 && (int) s.charAt(1) == 0) s = fixLinuxString(s);
         ArrayList list = new ArrayList();
         if (s.indexOf("href=\"") != -1 || s.indexOf("src=\"") != -1) {
           s = parseHTML(s);
           if (IJ.debugMode) IJ.log("  url: " + s);
           list.add(s);
           this.iterator = list.iterator();
           break;
         }
         BufferedReader br = new BufferedReader(new StringReader(s));
         String tmp;
         while (null != (tmp = br.readLine())) {
           tmp = java.net.URLDecoder.decode(tmp.replaceAll("\\+", "%2b"), "UTF-8");
           if (tmp.startsWith("file://")) tmp = tmp.substring(7);
           if (IJ.debugMode) IJ.log("  content: " + tmp);
           if (tmp.startsWith("http://")) list.add(s);
           else list.add(new File(tmp));
         }
         this.iterator = list.iterator();
         break;
       }
     }
     if (iterator != null) {
       Thread thread = new Thread(this, "DrawAndDrop");
       thread.setPriority(Math.max(thread.getPriority() - 1, Thread.MIN_PRIORITY));
       thread.start();
     }
   } catch (Exception e) {
     dtde.dropComplete(false);
     return;
   }
   dtde.dropComplete(true);
   if (flavors == null || flavors.length == 0) {
     if (IJ.isMacOSX())
       IJ.error(
           "First drag and drop ignored. Please try again. You can avoid this\n"
               + "problem by dragging to the toolbar instead of the status bar.");
     else IJ.error("Drag and drop failed");
   }
 }
  public void run(String arg) {
    ImageWindow iw = WindowManager.getCurrentWindow();
    pw = jutils.getPW4SelCopy(iw);
    String title = pw.getTitle();
    float[][] yvals = pw.getYValues();
    float[][] xvals = pw.getXValues();
    int length = yvals[0].length;
    if (pw.getShowErrors()) errs = pw.getErrors(0, false);
    int[] colors = pw.getColors();
    colors[0] = 0;
    ScriptEngineManager manager = new ScriptEngineManager();
    engine = manager.getEngineByName("js");
    ce = (Compilable) engine;
    // hitcounter=0;

    c2 = 0.0f;
    iterations = 0;
    checkc2 = false;

    double[] stats = new double[3];
    tempx = new float[length];
    tempdata = new float[length];
    System.arraycopy(xvals[0], 0, tempx, 0, length);
    System.arraycopy(yvals[0], 0, tempdata, 0, length);
    pw.addPoints(tempx, new float[tempx.length], false);
    series = pw.getNpts().length - 1;
    double[] params = new double[10];
    int[] fixes = {0, 0, 0, 1, 1, 1, 1, 1, 1, 1};
    init_options(params, fixes);
    if (!init_functions()) {
      return;
    }

    while (showoptions(params, fixes)) {
      NLLSfit_v2 fitclass;
      if (checkc2) {
        fitclass = new NLLSfit_v2(this, 0);
      } else {
        fitclass = new NLLSfit_v2(this, 0.0001, 50, 0.1);
      }
      float[] fit = fitclass.fitdata(params, fixes, constraints, yvals[0], weights, stats, true);
      pw.updateSeries(fit, series, false);
      c2 = (float) stats[1];
      iterations = (int) stats[0];
    }

    IJ.log("Chi Squared = " + (float) stats[1]);
    IJ.log("Iterations = " + (int) stats[0]);
    for (int i = 0; i < 10; i++) {
      IJ.log("P" + (i + 1) + " = " + (float) params[i] + " fixed = " + fixes[i]);
    }
    IJ.log("AIC = " + (float) stats[2]);
    // IJ.log("hits = "+hitcounter);
    set_options(params, fixes);
  }
Beispiel #6
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;
   }
 }
 boolean init_functions() {
   GenericDialog gd = new GenericDialog("Fitting Options");
   gd.addStringField("Extra Definitions", exdef, 50);
   gd.addCheckbox("Weight Using Plot Errors", false);
   gd.addStringField("Weighting Equation (y is for data)", weightfunction, 50);
   gd.addStringField("Fit_Equation", function, 50);
   gd.showDialog();
   if (gd.wasCanceled()) {
     return false;
   }
   exdef = gd.getNextString();
   boolean errweights = gd.getNextBoolean();
   weightfunction = gd.getNextString();
   function = gd.getNextString();
   // first initialize the weights
   weights = new float[tempdata.length];
   if (errweights
       || weightfunction.equals("")
       || weightfunction == null
       || weightfunction == "1.0") {
     if (errweights) {
       for (int i = 0; i < tempdata.length; i++) weights[i] = 1.0f / (errs[i] * errs[i]);
     } else {
       for (int i = 0; i < tempdata.length; i++) weights[i] = 1.0f;
     }
   } else {
     for (int i = 0; i < tempdata.length; i++) {
       String script =
           "y =" + tempdata[i] + "; " + "x =" + tempx[i] + "; " + "retval=" + weightfunction + ";";
       Double temp = new Double(0.0);
       try {
         temp = (Double) engine.eval(script);
       } catch (Exception e) {
         IJ.log(e.getMessage());
       }
       if (!(temp.isInfinite() || temp.isNaN())) {
         weights[i] = temp.floatValue();
       }
     }
   }
   // now compile the function script
   try {
     String script1 = exdef + "; retval=" + function + ";";
     cs = ce.compile(script1);
   } catch (Exception e) {
     IJ.log(e.toString());
     return false;
   }
   return true;
 }
  /**
   * Gets an IndexColorModel by loading a hardcoded LUT file. This is just a temporary expedient,
   * really belongs elsewhere.
   *
   * @return null or color model
   */
  public static IndexColorModel getIndexColorModel() {
    IndexColorModel colorModel = null;

    // 'getDirectory("luts")' works in IJ but not in NetBeans development
    String lutPath = IJ.getDirectory("luts");
    if (null == lutPath) {
      // when you run from a shortcut in Linux 'getDirectory("startup")'
      // gives you the directory of the link!
      final String startupPath = IJ.getDirectory("startup");
      lutPath = addSeparator(startupPath) + "luts";
    }
    lutPath = addSeparator(lutPath) + LUT;
    try {
      colorModel = LutLoader.open(lutPath);
    } catch (final IOException e) {
      IJ.showMessage("Missing LUT", "Install lifetime.lut from LOCI FIJI update site.");
      IJ.log("Problem loading LUT " + lutPath);
      return null;
    }
    // IJ converts the FloatProcessor to 8-bits and then uses this palette
    // for display. Unfortunately values less than or greater than the LUT
    // range still get displayed with LUT colors. To work around this, use
    // only 254 of the LUT colors. The first and last colors will represent
    // values less than and greater than the LUT range respectively.

    colorModel = PaletteFix.fixIndexColorModel(colorModel, Color.BLACK, Color.BLACK);
    return colorModel;
  }
Beispiel #9
0
 void enlargeArrays() {
   if (xp != null) {
     int[] xptemp = new int[maxPoints * 2];
     int[] yptemp = new int[maxPoints * 2];
     System.arraycopy(xp, 0, xptemp, 0, maxPoints);
     System.arraycopy(yp, 0, yptemp, 0, maxPoints);
     xp = xptemp;
     yp = yptemp;
   }
   if (xpf != null) {
     float[] xpftemp = new float[maxPoints * 2];
     float[] ypftemp = new float[maxPoints * 2];
     System.arraycopy(xpf, 0, xpftemp, 0, maxPoints);
     System.arraycopy(ypf, 0, ypftemp, 0, maxPoints);
     xpf = xpftemp;
     ypf = ypftemp;
   }
   int[] xp2temp = new int[maxPoints * 2];
   int[] yp2temp = new int[maxPoints * 2];
   System.arraycopy(xp2, 0, xp2temp, 0, maxPoints);
   System.arraycopy(yp2, 0, yp2temp, 0, maxPoints);
   xp2 = xp2temp;
   yp2 = yp2temp;
   if (IJ.debugMode) IJ.log("PolygonRoi: " + maxPoints + " points");
   maxPoints *= 2;
 }
Beispiel #10
0
 /* Are we tracing a one pixel wide line? Makes Legacy mode 8-connected instead of 4-connected */
 private boolean isLine(int xs, int ys) {
   int r = 5;
   int xmin = xs;
   int xmax = xs + 2 * r;
   if (xmax >= width) xmax = width - 1;
   int ymin = ys - r;
   if (ymin < 0) ymin = 0;
   int ymax = ys + r;
   if (ymax >= height) ymax = height - 1;
   int area = 0;
   int insideCount = 0;
   for (int x = xmin; (x <= xmax); x++)
     for (int y = ymin; y <= ymax; y++) {
       area++;
       if (inside(x, y)) insideCount++;
     }
   if (IJ.debugMode)
     IJ.log(
         (((double) insideCount) / area < 0.25 ? "line " : "blob ")
             + insideCount
             + " "
             + area
             + " "
             + IJ.d2s(((double) insideCount) / area));
   return ((double) insideCount) / area < 0.25;
 }
  // Creates a container of BinaryRegion objects
  // collects the region pixels from the label image
  // and computes the statistics for each region
  void collectRegions() {
    if (beVerbose) IJ.log("makeRegions()");
    int maxLabel = this.regionId;
    int startLabel = 1;
    BinaryRegion[] regionArray = new BinaryRegion[maxLabel + 1];
    for (int i = startLabel; i <= maxLabel; i++) {
      regionArray[i] = new BinaryRegion(i);
    }
    for (int v = 0; v < height; v++) {
      for (int u = 0; u < width; u++) {
        int lb = labelArray[v][u];
        if (lb >= startLabel && lb <= maxLabel && regionArray[lb] != null) {
          regionArray[lb].addPixel(u, v);
        }
      }
    }

    // create a list of regions to return, collect nonempty regions
    List<BinaryRegion> regionList = new LinkedList<BinaryRegion>();
    for (BinaryRegion r : regionArray) {
      if (r != null && r.getSize() > 0) {
        r.update(); // compute the statistics for this region
        regionList.add(r);
      }
    }
    allRegions = regionList;
  }
Beispiel #12
0
 /**
  * Logs a message to standard output (in batch mode) or to ImageJ standard logging facilities
  *
  * @see IJ#log(String)
  */
 public static void log(String s) {
   if (mode == BATCH) {
     System.out.println(s);
   } else {
     IJ.log(s);
   }
 }
Beispiel #13
0
 void updateMenus() {
   if (IJ.debugMode) {
     long start = System.currentTimeMillis();
     Menus.updateImageJMenus();
     IJ.log("Refresh Menus: " + (System.currentTimeMillis() - start) + " ms");
   } else Menus.updateImageJMenus();
 }
Beispiel #14
0
    public void actionPerformed(ActionEvent event) {
      System.out.println("Done listener");
      setVisible(false);
      try {
        // will transpose table before writing for ease...
        BufferedWriter output = new BufferedWriter(new FileWriter(defaultFile));

        output.newLine();
        for (int col = 0; col < table.getColumnCount(); col++) {
          // IJ.log("starting col: " + col + " of " + table.getColumnCount() +"total\n" );
          output.write(colNames.get(col) + "\t");
          for (int row = 0; row < table.getRowCount(); row++) {
            // IJ.log("starting row: " + row + " of " + table.getRowCount() +"total\n" );
            if (table.getValueAt(row, col) != null) {
              output.write((String) table.getValueAt(row, col));
              output.write(("\t"));
            }
            // IJ.log("writing " + table.getValueAt(row, col));
          }
          output.newLine();
        }
        // IJ.log("about to close prefs file");
        output.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        IJ.log("IO exception writing file: " + defaultFile);
        e.printStackTrace();
      }
      dispose();
    }
 public double[] fitfunc(double[] fitparams) {
   Bindings b = engine.createBindings();
   for (int i = 0; i < 10; i++) b.put("P" + (i + 1), fitparams[i]);
   /*String script1="P1="+fitparams[0]+"; "+
   "P2="+fitparams[1]+"; "+
   "P3="+fitparams[2]+"; "+
   "P4="+fitparams[3]+"; "+
   "P5="+fitparams[4]+"; "+
   "P6="+fitparams[5]+"; "+
   "P7="+fitparams[6]+"; "+
   "P8="+fitparams[7]+"; "+
   "P9="+fitparams[8]+"; "+
   "P10="+fitparams[9]+"; "+
   exdef+"; x=";
   String script2="; retval="+function+";";*/
   try {
     double[] temp = new double[tempx.length];
     for (int i = 0; i < tempx.length; i++) {
       // temp[i]=((Double)engine.eval(script1+(double)tempx[i]+script2)).doubleValue();
       b.put("x", tempx[i]);
       b.put("y", tempdata[i]);
       temp[i] = (Double) cs.eval(b);
     }
     return temp;
   } catch (Exception e) {
     IJ.log(e.getMessage());
     return null;
   }
 }
Beispiel #16
0
 /**
  * Notify any DialogListeners of changes having occurred If a listener returns false, do not call
  * further listeners and disable the OK button and preview Checkbox (if it exists). For
  * PlugInFilters, this ensures that the PlugInFilterRunner, which listens as the last one, is not
  * called if the PlugInFilter has detected invalid parameters. Thus, unnecessary calling the
  * run(ip) method of the PlugInFilter for preview is avoided in that case.
  */
 private void notifyListeners(AWTEvent e) {
   if (dialogListeners == null) return;
   boolean everythingOk = true;
   for (int i = 0; everythingOk && i < dialogListeners.size(); i++)
     try {
       resetCounters();
       if (!((DialogListener) dialogListeners.elementAt(i)).dialogItemChanged(this, e))
         everythingOk = false;
     } // disable further listeners if false (invalid parameters) returned
     catch (Exception err) { // for exceptions, don't cover the input by a window but
       IJ.beep(); // show them at in the "Log"
       IJ.log(
           "ERROR: "
               + err
               + "\nin DialogListener of "
               + dialogListeners.elementAt(i)
               + "\nat "
               + (err.getStackTrace()[0])
               + "\nfrom "
               + (err.getStackTrace()[1])); // requires Java 1.4
     }
   boolean workaroundOSXbug = IJ.isMacOSX() && okay != null && !okay.isEnabled() && everythingOk;
   if (previewCheckbox != null) previewCheckbox.setEnabled(everythingOk);
   if (okay != null) okay.setEnabled(everythingOk);
   if (workaroundOSXbug) repaint(); // OSX 10.4 bug delays update of enabled until the next input
 }
Beispiel #17
0
 /**
  * Reads the image from a URL and returns the pixel array (byte, short, int or float). Returns
  * null if there was an IO exception.
  */
 public Object readPixels(String url) {
   java.net.URL theURL;
   InputStream is;
   try {
     theURL = new URL(url);
   } catch (MalformedURLException e) {
     IJ.log("" + e);
     return null;
   }
   try {
     is = theURL.openStream();
   } catch (IOException e) {
     IJ.log("" + e);
     return null;
   }
   return readPixels(is);
 }
Beispiel #18
0
 public FileOpener(FileInfo fi) {
   this.fi = fi;
   if (fi != null) {
     width = fi.width;
     height = fi.height;
   }
   if (IJ.debugMode) IJ.log("FileInfo: " + fi);
 }
Beispiel #19
0
 public void dragOver(DropTargetDragEvent e) {
   if (IJ.debugMode) IJ.log("DragOver: " + e.getLocation());
   Point loc = e.getLocation();
   int buttonSize = Toolbar.getButtonSize();
   int width = IJ.getInstance().getSize().width;
   openAsVirtualStack = width - loc.x <= buttonSize;
   if (openAsVirtualStack) IJ.showStatus("<<Open as Virtual Stack>>");
   else IJ.showStatus("<<Drag and Drop>>");
 }
 public void dumpDataSet() {
   IJ.log(">>>>>>>>>>>>>>>>>>>>>>>> DataSet Dump:");
   if (dataSets != null) {
     for (int i = 0; i < numIDs; i++) {
       for (int j = 0; j < SLMModel.numPoints; j++) {
         IJ.log(
             i
                 + ", "
                 + j
                 + " == "
                 + dataSets[i].getMeasurement(j)
                 + " @ "
                 + dataSets[i].getSetting(j));
       }
     }
   }
   IJ.log("<<<<<<<<<<<<<<<<<<<<<<<< DataSet Dump");
 }
  public void loadEmbeddedMacros() {
    boolean altDown = IJ.altKeyDown(); // 3.8.2009
    boolean shiftDown = IJ.shiftKeyDown(); // 18.8.2009
    if (shiftDown) {
      shiftDown = shiftDown && true;
    }
    if (IJ.debugMode) {
      IJ.log("alt=" + altDown + "   shift=" + shiftDown);
    }
    String macros_text = null;
    String macroFileName = null;
    if (OJ.isProjectOpen) {
      DataOJ data = OJ.getData();
      String project_name = data.getName();

      String directory = data.getDirectory();
      macroFileName = project_name + ".txt";
      File macros_file = new File(directory, macroFileName);
      MacroInstaller mi = new MacroInstaller();
      // mechanism to remove manually loaded project files
      macros_text = OJ.getData().getLinkedMacroText(); // 18.3.2010
      boolean externalMacroExists = macros_file.exists() && macros_file.isFile();
      boolean internalMacroExists = (macros_text != null);
      if (!internalMacroExists && !externalMacroExists) {
        // mi.install(macros_text);16.9.2010
        return;
      }
      if (externalMacroExists && internalMacroExists) {
        IJ.showMessage("Project has internal macro, so external macro is ignored");
      }
      if (externalMacroExists && !internalMacroExists) {
        String thisVersion = IJ.getVersion();
        boolean is143d = thisVersion.compareToIgnoreCase("1.43d") >= 0;
        if (is143d) {
          String oldMacroName = ij.plugin.MacroInstaller.getFileName();
          if (oldMacroName != null && oldMacroName.equalsIgnoreCase(macroFileName)) {
            oldMacroName = oldMacroName + "";
            String macro = "macro 'Dummy Tool-Cf00O8822' {}\n"; // kill old tools
            mi.install(macro);

            String dir = IJ.getDirectory("macros") + "StartupMacros.txt";
            File startup_file = new File(IJ.getDirectory("macros"), "StartupMacros.txt");
            if (startup_file.exists()) {
              IJ.showMessage("Macros in \"" + macroFileName + "\" will appear under ObjectJ menu");
              mi.installFile(dir);
            }
            mi.setFileName(""); // 15.7.2009
          }
        }

        macros_text = UtilsOJ.readStringFromFile(macros_file);
      }
      OJ.getData().setLinkedMacroText(macros_text);
      doInstall(macros_text);
    }
  }
  void Bernsen(ImagePlus imp, int radius, double par1, double par2, boolean doIwhite) {
    // Bernsen recommends WIN_SIZE = 31 and CONTRAST_THRESHOLD = 15.
    //  1) Bernsen J. (1986) "Dynamic Thresholding of Grey-Level Images"
    //    Proc. of the 8th Int. Conf. on Pattern Recognition, pp. 1251-1255
    //  2) Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding
    //   Techniques and Quantitative Performance Evaluation" Journal of
    //   Electronic Imaging, 13(1): 146-165
    //  http://citeseer.ist.psu.edu/sezgin04survey.html
    // Ported to ImageJ plugin from E Celebi's fourier_0.8 routines
    // This version uses a circular local window, instead of a rectagular one
    ImagePlus Maximp, Minimp;
    ImageProcessor ip = imp.getProcessor(), ipMax, ipMin;
    int contrast_threshold = 15;
    int local_contrast;
    int mid_gray;
    byte object;
    byte backg;
    int temp;

    if (par1 != 0) {
      IJ.log("Bernsen: changed contrast_threshold from :" + contrast_threshold + "  to:" + par1);
      contrast_threshold = (int) par1;
    }

    if (doIwhite) {
      object = (byte) 0xff;
      backg = (byte) 0;
    } else {
      object = (byte) 0;
      backg = (byte) 0xff;
    }

    Maximp = duplicateImage(ip);
    ipMax = Maximp.getProcessor();
    RankFilters rf = new RankFilters();
    rf.rank(ipMax, radius, rf.MAX); // Maximum
    // Maximp.show();
    Minimp = duplicateImage(ip);
    ipMin = Minimp.getProcessor();
    rf.rank(ipMin, radius, rf.MIN); // Minimum
    // Minimp.show();
    byte[] pixels = (byte[]) ip.getPixels();
    byte[] max = (byte[]) ipMax.getPixels();
    byte[] min = (byte[]) ipMin.getPixels();

    for (int i = 0; i < pixels.length; i++) {
      local_contrast = (int) ((max[i] & 0xff) - (min[i] & 0xff));
      mid_gray = (int) ((min[i] & 0xff) + (max[i] & 0xff)) / 2;
      temp = (int) (pixels[i] & 0x0000ff);
      if (local_contrast < contrast_threshold)
        pixels[i] = (mid_gray >= 128) ? object : backg; // Low contrast region
      else pixels[i] = (temp >= mid_gray) ? object : backg;
    }
    // imp.updateAndDraw();
    return;
  }
 void drawAllROIs(Graphics g) {
   RoiManager rm = RoiManager.getInstance();
   if (rm == null) {
     rm = Interpreter.getBatchModeRoiManager();
     if (rm != null && rm.getList().getItemCount() == 0) rm = null;
   }
   if (rm == null) {
     // if (showAllList!=null)
     //	overlay = showAllList;
     showAllROIs = false;
     repaint();
     return;
   }
   initGraphics(g, null, showAllColor);
   Hashtable rois = rm.getROIs();
   java.awt.List list = rm.getList();
   boolean drawLabels = rm.getDrawLabels();
   currentRoi = null;
   int n = list.getItemCount();
   if (IJ.debugMode) IJ.log("paint: drawing " + n + " \"Show All\" ROIs");
   if (labelRects == null || labelRects.length != n) labelRects = new Rectangle[n];
   if (!drawLabels) showAllList = new Overlay();
   else showAllList = null;
   if (imp == null) return;
   int currentImage = imp.getCurrentSlice();
   int channel = 0, slice = 0, frame = 0;
   boolean hyperstack = imp.isHyperStack();
   if (hyperstack) {
     channel = imp.getChannel();
     slice = imp.getSlice();
     frame = imp.getFrame();
   }
   drawNames = Prefs.useNamesAsLabels;
   for (int i = 0; i < n; i++) {
     String label = list.getItem(i);
     Roi roi = (Roi) rois.get(label);
     if (roi == null) continue;
     if (showAllList != null) showAllList.add(roi);
     if (i < 200 && drawLabels && roi == imp.getRoi()) currentRoi = roi;
     if (Prefs.showAllSliceOnly && imp.getStackSize() > 1) {
       if (hyperstack && roi.getPosition() == 0) {
         int c = roi.getCPosition();
         int z = roi.getZPosition();
         int t = roi.getTPosition();
         if ((c == 0 || c == channel) && (z == 0 || z == slice) && (t == 0 || t == frame))
           drawRoi(g, roi, drawLabels ? i : -1);
       } else {
         int position = roi.getPosition();
         if (position == 0) position = getSliceNumber(roi.getName());
         if (position == 0 || position == currentImage) drawRoi(g, roi, drawLabels ? i : -1);
       }
     } else drawRoi(g, roi, drawLabels ? i : -1);
   }
   ((Graphics2D) g).setStroke(Roi.onePixelWide);
   drawNames = false;
 }
Beispiel #24
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.");
  }
Beispiel #25
0
 short[] readCompressed16bitImage(InputStream in) throws IOException {
   if (IJ.debugMode) IJ.log("ImageReader.read16bit, offset=" + fi.stripOffsets[0]);
   short[] pixels = new short[nPixels];
   int base = 0;
   short last = 0;
   for (int k = 0; k < fi.stripOffsets.length; k++) {
     // IJ.log("seek: "+fi.stripOffsets[k]+" "+fi.stripLengths[k]+"  "+(in instanceof
     // RandomAccessStream));
     if (in instanceof RandomAccessStream) ((RandomAccessStream) in).seek(fi.stripOffsets[k]);
     else if (k > 0) {
       long skip =
           (fi.stripOffsets[k] & 0xffffffffL)
               - (fi.stripOffsets[k - 1] & 0xffffffffL)
               - fi.stripLengths[k - 1];
       if (skip > 0L) in.skip(skip);
     }
     byte[] byteArray = new byte[fi.stripLengths[k]];
     int read = 0, left = byteArray.length;
     while (left > 0) {
       int r = in.read(byteArray, read, left);
       if (r == -1) {
         eofError();
         break;
       }
       read += r;
       left -= r;
     }
     byteArray = uncompress(byteArray);
     int pixelsRead = byteArray.length / bytesPerPixel;
     pixelsRead = pixelsRead - (pixelsRead % fi.width);
     int pmax = base + pixelsRead;
     if (pmax > nPixels) pmax = nPixels;
     if (fi.intelByteOrder) {
       for (int i = base, j = 0; i < pmax; i++, j += 2)
         pixels[i] = (short) (((byteArray[j + 1] & 0xff) << 8) | (byteArray[j] & 0xff));
     } else {
       for (int i = base, j = 0; i < pmax; i++, j += 2)
         pixels[i] = (short) (((byteArray[j] & 0xff) << 8) | (byteArray[j + 1] & 0xff));
     }
     if (fi.compression == FileInfo.LZW_WITH_DIFFERENCING) {
       for (int b = base; b < pmax; b++) {
         pixels[b] += last;
         last = b % fi.width == fi.width - 1 ? 0 : pixels[b];
       }
     }
     base += pixelsRead;
     showProgress(k + 1, fi.stripOffsets.length);
   }
   if (fi.fileType == FileInfo.GRAY16_SIGNED) {
     // convert to unsigned
     for (int i = 0; i < nPixels; i++) pixels[i] = (short) (pixels[i] + 32768);
   }
   return pixels;
 }
 public void measureROIs() {
   targets = new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0};
   // System.out.println("acquireImageAndMeasure");
   byte[] data = acqCtrl.acquireSampleImage();
   // measure intensity at ROIs
   ImageStatistics[] iStats =
       measureROIsIn(data, acqCtrl.getImageWidth(), acqCtrl.getImageHeight(), rois);
   for (int i = 0; i < numIDs; i++) {
     measurements[i] = Math.abs(iStats[i].meanInROI - slmModel.getZeroIntensity() - targets[i]);
   }
   IJ.log("\nMeasured ROIs:");
   for (int i = 0; i < numIDs; i++) {
     IJ.log(
         "   sector "
             + i
             + ": " // + settings[i]
             + " = "
             + measurements[i]);
   }
 }
Beispiel #27
0
 /**
  * Get a local thickness map from an ImagePlus with optional masking correction
  *
  * @param imp Binary ImagePlus
  * @param inv false if you want the thickness of the foreground and true if you want the thickness
  *     of the background
  * @param doMask true to apply a masking operation to enforce the map to contain thickness values
  *     only at coordinates where there is a corresponding input pixel
  * @return 32-bit ImagePlus containing a local thickness map
  */
 public ImagePlus getLocalThickness(ImagePlus imp, boolean inv, boolean doMask) {
   if (!(new ImageCheck()).isVoxelIsotropic(imp, 1E-3)) {
     IJ.log("Warning: voxels are anisotropic. Local thickness results will be inaccurate");
   }
   float[][] s = geometryToDistanceMap(imp, inv);
   distanceMaptoDistanceRidge(imp, s);
   distanceRidgetoLocalThickness(imp, s);
   ImagePlus impLTC = localThicknesstoCleanedUpLocalThickness(imp, s);
   if (doMask) impLTC = trimOverhang(imp, impLTC, inv);
   return impLTC;
 }
Beispiel #28
0
 protected boolean split(Object3DGui og) {
   if (!(this instanceof NucleusManager) && og.getChannel() instanceof Nucleus) {
     if (Core.GUIMode) ij.IJ.log("Cannont split nucleus!");
     return false;
   }
   Object3DGui[] newObjects = og.split(splitRad.getFloatValue(2), splitDist.getFloatValue(5));
   if (newObjects.length == 0) {
     if (Core.GUIMode) ij.IJ.log("Object couldn't be split");
     return false;
   }
   Object3D[] objs = og.getChannel().getObjects();
   int nextLabel = objs[objs.length - 1].getValue() + 1;
   for (Object3DGui o : newObjects) {
     o.changeLabel(nextLabel);
     this.listModel.addElement(o); // TODO le mettre a la fin des objets du channel..
     nextLabel++;
   }
   og.getChannel().getSegmented().updateDisplay();
   return true;
 }
Beispiel #29
0
 boolean setProperties(String title, Roi roi) {
   Frame f = WindowManager.getFrontWindow();
   if (f != null && f.getTitle().indexOf("3D Viewer") != -1) return false;
   if (roi == null) {
     IJ.error("This command requires a selection.");
     return false;
   }
   RoiProperties rp = new RoiProperties(title, roi);
   boolean ok = rp.showDialog();
   if (IJ.debugMode) IJ.log(roi.getDebugInfo());
   return ok;
 }
Beispiel #30
0
 /**
  * Open a file. If it's a directory, ask to open all images as a sequence in a stack or
  * individually.
  */
 public void openFile(File f) {
   if (IJ.debugMode) IJ.log("DragAndDrop.openFile: " + f);
   try {
     if (null == f) return;
     String path = f.getCanonicalPath();
     if (f.exists()) {
       if (f.isDirectory()) openDirectory(f, path);
       else {
         if (openAsVirtualStack && (path.endsWith(".tif") || path.endsWith(".TIF")))
           (new FileInfoVirtualStack()).run(path);
         else (new Opener()).openAndAddToRecent(path);
         OpenDialog.setLastDirectory(f.getParent() + File.separator);
         OpenDialog.setLastName(f.getName());
       }
     } else {
       IJ.log("File not found: " + path);
     }
   } catch (Throwable e) {
     if (!Macro.MACRO_CANCELED.equals(e.getMessage())) IJ.handleException(e);
   }
 }