public void run(String arg) { ImageJ ij = IJ.getInstance(); ij.setDropTarget(null); new DropTarget(ij, this); new DropTarget(Toolbar.getInstance(), this); new DropTarget(ij.getStatusBar(), this); }
public int showDialog(ImagePlus imp, String command, PlugInFilterRunner pfr) { this.pfr = pfr; String macroOptions = Macro.getOptions(); if (macroOptions != null) { if (macroOptions.indexOf(" interpolate") != -1) macroOptions.replaceAll(" interpolate", " interpolation=Bilinear"); else if (macroOptions.indexOf(" interpolation=") == -1) macroOptions = macroOptions + " interpolation=None"; Macro.setOptions(macroOptions); } gd = new GenericDialog("Rotate", IJ.getInstance()); gd.addNumericField("Angle (degrees):", angle, (int) angle == angle ? 1 : 2); gd.addNumericField("Grid Lines:", gridLines, 0); gd.addChoice("Interpolation:", methods, methods[interpolationMethod]); if (bitDepth == 8 || bitDepth == 24) gd.addCheckbox("Fill with Background Color", fillWithBackground); if (canEnlarge) gd.addCheckbox("Enlarge Image to Fit Result", enlarge); else enlarge = false; gd.addPreviewCheckbox(pfr); gd.addDialogListener(this); gd.showDialog(); drawGridLines(0); if (gd.wasCanceled()) { return DONE; } if (!enlarge) flags |= KEEP_PREVIEW; // standard filter without enlarge else if (imp.getStackSize() == 1) flags |= NO_CHANGES; // undoable as a "compound filter" return IJ.setupDialog(imp, flags); }
public Channels() { super("Channels"); if (instance != null) { instance.toFront(); return; } WindowManager.addWindow(this); instance = this; GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); setLayout(gridbag); int y = 0; c.gridx = 0; c.gridy = y++; c.gridwidth = 1; c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.CENTER; int margin = 32; if (IJ.isMacOSX()) margin = 20; c.insets = new Insets(10, margin, 10, margin); choice = new Choice(); for (int i = 0; i < modes.length; i++) choice.addItem(modes[i]); choice.select(0); choice.addItemListener(this); add(choice, c); CompositeImage ci = getImage(); int nCheckBoxes = ci != null ? ci.getNChannels() : 3; if (nCheckBoxes > CompositeImage.MAX_CHANNELS) nCheckBoxes = CompositeImage.MAX_CHANNELS; checkbox = new Checkbox[nCheckBoxes]; for (int i = 0; i < nCheckBoxes; i++) { checkbox[i] = new Checkbox("Channel " + (i + 1), true); c.insets = new Insets(0, 25, i < nCheckBoxes - 1 ? 0 : 10, 5); c.gridy = y++; add(checkbox[i], c); checkbox[i].addItemListener(this); } c.insets = new Insets(0, 15, 10, 15); c.fill = GridBagConstraints.NONE; c.gridy = y++; moreButton = new Button(moreLabel); moreButton.addActionListener(this); add(moreButton, c); update(); pm = new PopupMenu(); for (int i = 0; i < menuItems.length; i++) addPopupItem(menuItems[i]); add(pm); addKeyListener(IJ.getInstance()); // ImageJ handles keyboard shortcuts setResizable(false); pack(); if (location == null) { GUI.center(this); location = getLocation(); } else setLocation(location); show(); }
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>>"); }
/** * Builds dialog to query users for projection parameters. * * @param start starting slice to display * @param stop last slice */ protected GenericDialog buildControlDialog(int start, int stop) { GenericDialog gd = new GenericDialog("ZProjection", IJ.getInstance()); gd.addNumericField("Start slice:", startSlice, 0 /*digits*/); gd.addNumericField("Stop slice:", stopSlice, 0 /*digits*/); gd.addChoice("Projection type", METHODS, METHODS[method]); if (isHyperstack && imp.getNFrames() > 1 && imp.getNSlices() > 1) gd.addCheckbox("All time frames", allTimeFrames); return gd; }
// Miscellaneous Options void miscOptions() { String key = IJ.isMacintosh() ? "command" : "control"; GenericDialog gd = new GenericDialog("Miscellaneous Options", IJ.getInstance()); gd.addStringField("Divide by zero value:", "" + FloatBlitter.divideByZeroValue, 10); gd.addCheckbox("Use pointer cursor", Prefs.usePointerCursor); gd.addCheckbox("Hide \"Process Stack?\" dialog", IJ.hideProcessStackDialog); gd.addCheckbox("Require " + key + " key for shortcuts", Prefs.requireControlKey); gd.addCheckbox("Move isolated plugins to Misc. menu", Prefs.moveToMisc); if (!IJ.isMacOSX()) gd.addCheckbox("Run single instance listener", Prefs.runSocketListener); gd.addCheckbox("Enhanced line tool", Prefs.enhancedLineTool); gd.addCheckbox("Reverse CZT order of \">\" and \"<\"", Prefs.reverseNextPreviousOrder); gd.addCheckbox("Debug mode", IJ.debugMode); gd.addHelp(IJ.URL + "/docs/menus/edit.html#misc"); gd.showDialog(); if (gd.wasCanceled()) return; String divValue = gd.getNextString(); if (divValue.equalsIgnoreCase("infinity") || divValue.equalsIgnoreCase("infinite")) FloatBlitter.divideByZeroValue = Float.POSITIVE_INFINITY; else if (divValue.equalsIgnoreCase("NaN")) FloatBlitter.divideByZeroValue = Float.NaN; else if (divValue.equalsIgnoreCase("max")) FloatBlitter.divideByZeroValue = Float.MAX_VALUE; else { Float f; try { f = new Float(divValue); } catch (NumberFormatException e) { f = null; } if (f != null) FloatBlitter.divideByZeroValue = f.floatValue(); } IJ.register(FloatBlitter.class); Prefs.usePointerCursor = gd.getNextBoolean(); IJ.hideProcessStackDialog = gd.getNextBoolean(); Prefs.requireControlKey = gd.getNextBoolean(); Prefs.moveToMisc = gd.getNextBoolean(); if (!IJ.isMacOSX()) Prefs.runSocketListener = gd.getNextBoolean(); Prefs.enhancedLineTool = gd.getNextBoolean(); Prefs.reverseNextPreviousOrder = gd.getNextBoolean(); IJ.setDebugMode(gd.getNextBoolean()); }
/** 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; } }
public void run(String arg) { GenericDialog gd = new GenericDialog("Options"); double sfreq = 20000.0; gd.addNumericField("Sampling Frequency?", sfreq, 1, 10, null); String[] psfchoice = {"3D Gaussian", "Gaus-Lorentz^2", "2D Gaussian"}; gd.addChoice("PSF Type?", psfchoice, psfchoice[0]); String[] filetypechoice = { "Confocor 3 raw", "Short binary trajectory", "PlotWindow trajectory", "Ascii Text File" }; gd.addChoice("File Type?", filetypechoice, filetypechoice[0]); boolean ch2green = true; gd.addCheckbox("Ch2 is green?", ch2green); gd.showDialog(); if (gd.wasCanceled()) { return; } sfreq = gd.getNextNumber(); int psfflag = gd.getNextChoiceIndex(); int fileflag = gd.getNextChoiceIndex(); ch2green = gd.getNextBoolean(); int nfiles = 0; Object[] histograms = null; int xmax = 0; int ymax = 0; String[] names = null; if (fileflag < 2) { jdataio ioclass = new jdataio(); File[] filearray = ioclass.openfiles(OpenDialog.getDefaultDirectory(), IJ.getInstance()); if (filearray.length == 0) { return; } String dir = filearray[0].getAbsolutePath(); int sepindex = dir.lastIndexOf(File.separator); String newdir = dir.substring(0, sepindex + 1); OpenDialog.setDefaultDirectory(newdir); nfiles = filearray.length / 2; if (nfiles > 25) { nfiles = 25; } histograms = new Object[nfiles]; names = organize_c3_files(filearray); for (int i = 0; i < nfiles; i++) { try { int length1 = (int) (((double) filearray[2 * i].length() - 128.0) / 4.0); int length2 = (int) (((double) filearray[2 * i + 1].length() - 128.0) / 4.0); int length3 = (int) (((double) filearray[2 * i].length()) / 2.0); int length4 = (int) (((double) filearray[2 * i + 1].length()) / 2.0); InputStream instream = new BufferedInputStream(new FileInputStream(filearray[2 * i])); InputStream instream2 = new BufferedInputStream(new FileInputStream(filearray[2 * i + 1])); if (fileflag == 0) { int[] pmdata = new int[length1]; int[] pmdata2 = new int[length2]; if (!ioclass.skipstreambytes(instream, 128)) { showioerror(); instream.close(); return; } if (!ioclass.skipstreambytes(instream2, 128)) { showioerror(); instream2.close(); return; } if (!ioclass.readintelintfile(instream, length1, pmdata)) { showioerror(); instream.close(); return; } if (!ioclass.readintelintfile(instream2, length2, pmdata2)) { showioerror(); instream2.close(); return; } if (ch2green) { histograms[i] = (new pmodeconvert()).pm2pch(pmdata2, pmdata, sfreq, 20000000); } else { histograms[i] = (new pmodeconvert()).pm2pch(pmdata, pmdata2, sfreq, 20000000); } } else { float[] tmdata = new float[length3]; float[] tmdata2 = new float[length4]; if (!ioclass.readintelshortfile(instream, length3, tmdata)) { showioerror(); instream.close(); return; } if (!ioclass.readintelshortfile(instream2, length4, tmdata2)) { showioerror(); instream2.close(); return; } if (ch2green) { histograms[i] = (new pmodeconvert()).create_2Dhistogram(tmdata2, tmdata); } else { histograms[i] = (new pmodeconvert()).create_2Dhistogram(tmdata, tmdata2); } } if (((float[][]) histograms[i]).length > xmax) { xmax = ((float[][]) histograms[i]).length; } if (((float[][]) histograms[i])[0].length > ymax) { ymax = ((float[][]) histograms[i])[0].length; } instream.close(); instream2.close(); } catch (IOException e) { showioerror(); return; } } } else { if (fileflag == 2) { ImageWindow iw = WindowManager.getCurrentWindow(); float[][] trajectories = (float[][]) jutils.runPW4VoidMethod(iw, "getYValues"); float[][] tempxvals = (float[][]) jutils.runPW4VoidMethod(iw, "getXValues"); sfreq = 1.0 / ((double) tempxvals[0][1]); nfiles = trajectories.length / 2; if (nfiles > 25) { nfiles = 25; } names = new String[nfiles + 1]; names[nfiles] = "avg"; histograms = new Object[nfiles]; for (int i = 0; i < nfiles; i++) { names[i] = "trajectory " + (i + 1); if (ch2green) { histograms[i] = (new pmodeconvert()) .create_2Dhistogram(trajectories[2 * i + 1], trajectories[2 * i]); } else { histograms[i] = (new pmodeconvert()) .create_2Dhistogram(trajectories[2 * i], trajectories[2 * i + 1]); } if (((float[][]) histograms[i]).length > xmax) { xmax = ((float[][]) histograms[i]).length; } if (((float[][]) histograms[i])[0].length > ymax) { ymax = ((float[][]) histograms[i])[0].length; } } } else { // here we read tab delimited lines from files jdataio ioclass = new jdataio(); File[] filearray = ioclass.openfiles(OpenDialog.getDefaultDirectory(), IJ.getInstance()); if (filearray.length == 0) { return; } String dir = filearray[0].getAbsolutePath(); int sepindex = dir.lastIndexOf(File.separator); String newdir = dir.substring(0, sepindex + 1); OpenDialog.setDefaultDirectory(newdir); nfiles = filearray.length; if (nfiles > 25) { nfiles = 25; } histograms = new Object[nfiles]; names = new String[nfiles + 1]; names[nfiles] = "avg"; for (int i = 0; i < nfiles; i++) { try { names[i] = filearray[i].getName(); BufferedReader d = new BufferedReader(new FileReader(filearray[i])); String[] lines = new String[256]; int counter = 0; do { lines[counter] = d.readLine(); counter++; } while ((lines[counter - 1] != null && lines[counter - 1] != "") && counter < 256); int numcolumns = 0; for (int j = 0; j < counter - 1; j++) { int temp = getncolumns(lines[j]); if (temp > numcolumns) { numcolumns = temp; } } float[][] temphist2 = null; if (ch2green) { temphist2 = new float[numcolumns][counter - 1]; } else { temphist2 = new float[counter - 1][numcolumns]; } for (int k = 0; k < counter - 1; k++) { float[] temp = tab_delim2float(lines[k]); for (int j = 0; j < numcolumns; j++) { if (ch2green) { temphist2[j][k] = temp[j]; } else { temphist2[k][j] = temp[j]; } } } histograms[i] = temphist2; d.close(); } catch (IOException e) { showioerror(); return; } } for (int i = 0; i < nfiles; i++) { if (((float[][]) histograms[i]).length > xmax) { xmax = ((float[][]) histograms[i]).length; } if (((float[][]) histograms[i])[0].length > ymax) { ymax = ((float[][]) histograms[i])[0].length; } } } } // note that here x is green and y is red float[][][] pch = new float[nfiles][xmax][ymax]; for (int i = 0; i < nfiles; i++) { for (int j = 0; j < ((float[][]) histograms[i]).length; j++) { for (int k = 0; k < ((float[][]) histograms[i])[j].length; k++) { pch[i][j][k] = ((float[][]) histograms[i])[j][k]; } } } final PCH2DFitWindow cw = new PCH2DFitWindow(); cw.init(names, pch, psfflag); final Frame f = new Frame("PCH 2D Analysis"); f.setLocation(10, 10); f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { f.dispose(); } }); f.add(cw); f.pack(); f.setResizable(false); Insets ins = f.getInsets(); cw.totalSize.height = PCH2DFitWindow.H + ins.bottom + ins.top + 65; cw.totalSize.width = PCH2DFitWindow.WR + ins.left + ins.right; f.setSize(cw.totalSize); f.setVisible(true); cw.requestFocus(); }
public static void main(String args[]) { if (System.getProperty("java.version").substring(0, 3).compareTo("1.5") < 0) { javax.swing.JOptionPane.showMessageDialog( null, "ImageJ " + VERSION + " requires Java 1.5 or later."); System.exit(0); } boolean noGUI = false; int mode = STANDALONE; arguments = args; // System.setProperty("file.encoding", "UTF-8"); int nArgs = args != null ? args.length : 0; boolean commandLine = false; for (int i = 0; i < nArgs; i++) { String arg = args[i]; if (arg == null) continue; if (args[i].startsWith("-")) { if (args[i].startsWith("-batch")) noGUI = true; else if (args[i].startsWith("-debug")) IJ.setDebugMode(true); else if (args[i].startsWith("-ijpath") && i + 1 < nArgs) { if (IJ.debugMode) IJ.log("-ijpath: " + args[i + 1]); Prefs.setHomeDir(args[i + 1]); commandLine = true; args[i + 1] = null; } else if (args[i].startsWith("-port")) { int delta = (int) Tools.parseDouble(args[i].substring(5, args[i].length()), 0.0); commandLine = true; if (delta == 0) mode = EMBEDDED; else if (delta > 0 && DEFAULT_PORT + delta < 65536) port = DEFAULT_PORT + delta; } } } // If existing ImageJ instance, pass arguments to it and quit. boolean passArgs = mode == STANDALONE && !noGUI; if (IJ.isMacOSX() && !commandLine) passArgs = false; if (passArgs && isRunning(args)) return; ImageJ ij = IJ.getInstance(); if (!noGUI && (ij == null || (ij != null && !ij.isShowing()))) { ij = new ImageJ(null, mode); ij.exitWhenQuitting = true; } int macros = 0; for (int i = 0; i < nArgs; i++) { String arg = args[i]; if (arg == null) continue; if (arg.startsWith("-")) { if ((arg.startsWith("-macro") || arg.startsWith("-batch")) && i + 1 < nArgs) { String arg2 = i + 2 < nArgs ? args[i + 2] : null; Prefs.commandLineMacro = true; if (noGUI && args[i + 1].endsWith(".js")) Interpreter.batchMode = true; IJ.runMacroFile(args[i + 1], arg2); break; } else if (arg.startsWith("-eval") && i + 1 < nArgs) { String rtn = IJ.runMacro(args[i + 1]); if (rtn != null) System.out.print(rtn); args[i + 1] = null; } else if (arg.startsWith("-run") && i + 1 < nArgs) { IJ.run(args[i + 1]); args[i + 1] = null; } } else if (macros == 0 && (arg.endsWith(".ijm") || arg.endsWith(".txt"))) { IJ.runMacroFile(arg); macros++; } else if (arg.length() > 0 && arg.indexOf("ij.ImageJ") == -1) { File file = new File(arg); IJ.open(file.getAbsolutePath()); } } if (IJ.debugMode && IJ.getInstance() == null) new JavaProperties().run(""); if (noGUI) System.exit(0); }
/** * Performs particle analysis on the specified ImagePlus and ImageProcessor. Returns false if * there is an error. */ public boolean analyze(ImagePlus imp, ImageProcessor ip) { if (this.imp == null) this.imp = imp; showResults = (options & SHOW_RESULTS) != 0; excludeEdgeParticles = (options & EXCLUDE_EDGE_PARTICLES) != 0; resetCounter = (options & CLEAR_WORKSHEET) != 0; showProgress = (options & SHOW_PROGRESS) != 0; floodFill = (options & INCLUDE_HOLES) == 0; recordStarts = (options & RECORD_STARTS) != 0; addToManager = (options & ADD_TO_MANAGER) != 0; displaySummary = (options & DISPLAY_SUMMARY) != 0; inSituShow = (options & IN_SITU_SHOW) != 0; outputImage = null; ip.snapshot(); ip.setProgressBar(null); if (Analyzer.isRedirectImage()) { redirectImp = Analyzer.getRedirectImage(imp); if (redirectImp == null) return false; int depth = redirectImp.getStackSize(); if (depth > 1 && depth == imp.getStackSize()) { ImageStack redirectStack = redirectImp.getStack(); redirectIP = redirectStack.getProcessor(imp.getCurrentSlice()); } else redirectIP = redirectImp.getProcessor(); } else if (imp.getType() == ImagePlus.COLOR_RGB) { ImagePlus original = (ImagePlus) imp.getProperty("OriginalImage"); if (original != null && original.getWidth() == imp.getWidth() && original.getHeight() == imp.getHeight()) { redirectImp = original; redirectIP = original.getProcessor(); } } if (!setThresholdLevels(imp, ip)) return false; width = ip.getWidth(); height = ip.getHeight(); if (!(showChoice == NOTHING || showChoice == OVERLAY_OUTLINES || showChoice == OVERLAY_MASKS)) { blackBackground = Prefs.blackBackground && inSituShow; if (slice == 1) outlines = new ImageStack(width, height); if (showChoice == ROI_MASKS) drawIP = new ShortProcessor(width, height); else drawIP = new ByteProcessor(width, height); drawIP.setLineWidth(lineWidth); if (showChoice == ROI_MASKS) { } // Place holder for now... else if (showChoice == MASKS && !blackBackground) drawIP.invertLut(); else if (showChoice == OUTLINES) { if (!inSituShow) { if (customLut == null) makeCustomLut(); drawIP.setColorModel(customLut); } drawIP.setFont(new Font("SansSerif", Font.PLAIN, fontSize)); if (fontSize > 12 && inSituShow) drawIP.setAntialiasedText(true); } outlines.addSlice(null, drawIP); if (showChoice == ROI_MASKS || blackBackground) { drawIP.setColor(Color.black); drawIP.fill(); drawIP.setColor(Color.white); } else { drawIP.setColor(Color.white); drawIP.fill(); drawIP.setColor(Color.black); } } calibration = redirectImp != null ? redirectImp.getCalibration() : imp.getCalibration(); if (rt == null) { rt = Analyzer.getResultsTable(); analyzer = new Analyzer(imp); } else analyzer = new Analyzer(imp, measurements, rt); if (resetCounter && slice == 1) { if (!Analyzer.resetCounter()) return false; } beginningCount = Analyzer.getCounter(); byte[] pixels = null; if (ip instanceof ByteProcessor) pixels = (byte[]) ip.getPixels(); if (r == null) { r = ip.getRoi(); mask = ip.getMask(); if (displaySummary) { if (mask != null) totalArea = ImageStatistics.getStatistics(ip, AREA, calibration).area; else totalArea = r.width * calibration.pixelWidth * r.height * calibration.pixelHeight; } } minX = r.x; maxX = r.x + r.width; minY = r.y; maxY = r.y + r.height; if (r.width < width || r.height < height || mask != null) { if (!eraseOutsideRoi(ip, r, mask)) return false; } int offset; double value; int inc = Math.max(r.height / 25, 1); int mi = 0; ImageWindow win = imp.getWindow(); if (win != null) win.running = true; if (measurements == 0) measurements = Analyzer.getMeasurements(); if (showChoice == ELLIPSES) measurements |= ELLIPSE; measurements &= ~LIMIT; // ignore "Limit to Threshold" roiNeedsImage = (measurements & PERIMETER) != 0 || (measurements & SHAPE_DESCRIPTORS) != 0 || (measurements & FERET) != 0; particleCount = 0; wand = new Wand(ip); pf = new PolygonFiller(); if (floodFill) { ImageProcessor ipf = ip.duplicate(); ipf.setValue(fillColor); ff = new FloodFiller(ipf); } roiType = Wand.allPoints() ? Roi.FREEROI : Roi.TRACED_ROI; for (int y = r.y; y < (r.y + r.height); y++) { offset = y * width; for (int x = r.x; x < (r.x + r.width); x++) { if (pixels != null) value = pixels[offset + x] & 255; else if (imageType == SHORT) value = ip.getPixel(x, y); else value = ip.getPixelValue(x, y); if (value >= level1 && value <= level2) analyzeParticle(x, y, imp, ip); } if (showProgress && ((y % inc) == 0)) IJ.showProgress((double) (y - r.y) / r.height); if (win != null) canceled = !win.running; if (canceled) { Macro.abort(); break; } } if (showProgress) IJ.showProgress(1.0); if (showResults) rt.updateResults(); imp.killRoi(); ip.resetRoi(); ip.reset(); if (displaySummary && IJ.getInstance() != null) updateSliceSummary(); if (addToManager && roiManager != null) roiManager.setEditMode(imp, true); maxParticleCount = (particleCount > maxParticleCount) ? particleCount : maxParticleCount; totalCount += particleCount; if (!canceled) showResults(); return true; }
String getInfo(ImagePlus imp, ImageProcessor ip) { String s = new String(""); if (IJ.getInstance() != null) s += IJ.getInstance().getInfo() + "\n \n"; s += "Title: " + imp.getTitle() + "\n"; Calibration cal = imp.getCalibration(); int stackSize = imp.getStackSize(); int channels = imp.getNChannels(); int slices = imp.getNSlices(); int frames = imp.getNFrames(); int digits = imp.getBitDepth() == 32 ? 4 : 0; int dp, dp2; boolean nonUniformUnits = !cal.getXUnit().equals(cal.getYUnit()); String xunit = cal.getXUnit(); String yunit = cal.getYUnit(); String zunit = cal.getZUnit(); if (cal.scaled()) { String xunits = cal.getUnits(); String yunits = xunits; String zunits = xunits; if (nonUniformUnits) { xunits = xunit; yunits = yunit; zunits = zunit; } double pw = imp.getWidth() * cal.pixelWidth; double ph = imp.getHeight() * cal.pixelHeight; s += "Width: " + d2s(pw) + " " + xunits + " (" + imp.getWidth() + ")\n"; s += "Height: " + d2s(ph) + " " + yunits + " (" + imp.getHeight() + ")\n"; if (slices > 1) { double pd = slices * cal.pixelDepth; s += "Depth: " + d2s(pd) + " " + zunits + " (" + slices + ")\n"; } s += "Size: " + ImageWindow.getImageSize(imp) + "\n"; double xResolution = 1.0 / cal.pixelWidth; double yResolution = 1.0 / cal.pixelHeight; if (xResolution == yResolution) s += "Resolution: " + d2s(xResolution) + " pixels per " + xunit + "\n"; else { s += "X Resolution: " + d2s(xResolution) + " pixels per " + xunit + "\n"; s += "Y Resolution: " + d2s(yResolution) + " pixels per " + yunit + "\n"; } } else { s += "Width: " + imp.getWidth() + " pixels\n"; s += "Height: " + imp.getHeight() + " pixels\n"; if (stackSize > 1) s += "Depth: " + slices + " pixels\n"; s += "Size: " + ImageWindow.getImageSize(imp) + "\n"; } if (stackSize > 1) { String vunit = cal.getUnit() + "^3"; if (nonUniformUnits) vunit = "(" + xunit + " x " + yunit + " x " + zunit + ")"; s += "Voxel size: " + d2s(cal.pixelWidth) + "x" + d2s(cal.pixelHeight) + "x" + d2s(cal.pixelDepth) + " " + vunit + "\n"; } else { String punit = cal.getUnit() + "^2"; if (nonUniformUnits) punit = "(" + xunit + " x " + yunit + ")"; dp = Tools.getDecimalPlaces(cal.pixelWidth, cal.pixelHeight); s += "Pixel size: " + d2s(cal.pixelWidth) + "x" + d2s(cal.pixelHeight) + " " + punit + "\n"; } s += "ID: " + imp.getID() + "\n"; int type = imp.getType(); switch (type) { case ImagePlus.GRAY8: s += "Bits per pixel: 8 "; String lut = "LUT"; if (imp.getProcessor().isColorLut()) lut = "color " + lut; else lut = "grayscale " + lut; if (imp.isInvertedLut()) lut = "inverting " + lut; s += "(" + lut + ")\n"; if (imp.getNChannels() > 1) s += displayRanges(imp); else s += "Display range: " + (int) ip.getMin() + "-" + (int) ip.getMax() + "\n"; break; case ImagePlus.GRAY16: case ImagePlus.GRAY32: if (type == ImagePlus.GRAY16) { String sign = cal.isSigned16Bit() ? "signed" : "unsigned"; s += "Bits per pixel: 16 (" + sign + ")\n"; } else s += "Bits per pixel: 32 (float)\n"; if (imp.getNChannels() > 1) s += displayRanges(imp); else { s += "Display range: "; double min = ip.getMin(); double max = ip.getMax(); if (cal.calibrated()) { min = cal.getCValue((int) min); max = cal.getCValue((int) max); } s += d2s(min) + " - " + d2s(max) + "\n"; } break; case ImagePlus.COLOR_256: s += "Bits per pixel: 8 (color LUT)\n"; break; case ImagePlus.COLOR_RGB: s += "Bits per pixel: 32 (RGB)\n"; break; } double interval = cal.frameInterval; double fps = cal.fps; if (stackSize > 1) { ImageStack stack = imp.getStack(); int slice = imp.getCurrentSlice(); String number = slice + "/" + stackSize; String label = stack.getShortSliceLabel(slice); if (label != null && label.length() > 0) label = " (" + label + ")"; else label = ""; if (interval > 0.0 || fps != 0.0) { s += "Frame: " + number + label + "\n"; if (fps != 0.0) { String sRate = Math.abs(fps - Math.round(fps)) < 0.00001 ? IJ.d2s(fps, 0) : IJ.d2s(fps, 5); s += "Frame rate: " + sRate + " fps\n"; } if (interval != 0.0) s += "Frame interval: " + ((int) interval == interval ? IJ.d2s(interval, 0) : IJ.d2s(interval, 5)) + " " + cal.getTimeUnit() + "\n"; } else s += "Image: " + number + label + "\n"; if (imp.isHyperStack()) { if (channels > 1) s += " Channel: " + imp.getChannel() + "/" + channels + "\n"; if (slices > 1) s += " Slice: " + imp.getSlice() + "/" + slices + "\n"; if (frames > 1) s += " Frame: " + imp.getFrame() + "/" + frames + "\n"; } if (imp.isComposite()) { if (!imp.isHyperStack() && channels > 1) s += " Channels: " + channels + "\n"; String mode = ((CompositeImage) imp).getModeAsString(); s += " Composite mode: \"" + mode + "\"\n"; } } if (ip.getMinThreshold() == ImageProcessor.NO_THRESHOLD) s += "No threshold\n"; else { double lower = ip.getMinThreshold(); double upper = ip.getMaxThreshold(); if (cal.calibrated()) { lower = cal.getCValue((int) lower); upper = cal.getCValue((int) upper); } s += "Threshold: " + d2s(lower) + "-" + d2s(upper) + "\n"; } ImageCanvas ic = imp.getCanvas(); double mag = ic != null ? ic.getMagnification() : 1.0; if (mag != 1.0) s += "Magnification: " + IJ.d2s(mag, 2) + "\n"; if (cal.calibrated()) { s += " \n"; int curveFit = cal.getFunction(); s += "Calibration function: "; if (curveFit == Calibration.UNCALIBRATED_OD) s += "Uncalibrated OD\n"; else if (curveFit == Calibration.CUSTOM) s += "Custom lookup table\n"; else s += CurveFitter.fList[curveFit] + "\n"; double[] c = cal.getCoefficients(); if (c != null) { s += " a: " + IJ.d2s(c[0], 6) + "\n"; s += " b: " + IJ.d2s(c[1], 6) + "\n"; if (c.length >= 3) s += " c: " + IJ.d2s(c[2], 6) + "\n"; if (c.length >= 4) s += " c: " + IJ.d2s(c[3], 6) + "\n"; if (c.length >= 5) s += " c: " + IJ.d2s(c[4], 6) + "\n"; } s += " Unit: \"" + cal.getValueUnit() + "\"\n"; } else s += "Uncalibrated\n"; FileInfo fi = imp.getOriginalFileInfo(); if (fi != null) { if (fi.url != null && !fi.url.equals("")) s += "URL: " + fi.url + "\n"; else if (fi.directory != null && fi.fileName != null) s += "Path: " + fi.directory + fi.fileName + "\n"; } ImageWindow win = imp.getWindow(); if (win != null) { Point loc = win.getLocation(); Dimension screen = IJ.getScreenSize(); s += "Screen location: " + loc.x + "," + loc.y + " (" + screen.width + "x" + screen.height + ")\n"; } String zOrigin = stackSize > 1 || cal.zOrigin != 0.0 ? "," + d2s(cal.zOrigin) : ""; String origin = d2s(cal.xOrigin) + "," + d2s(cal.yOrigin) + zOrigin; if (!origin.equals("0,0") || cal.getInvertY()) s += "Coordinate origin: " + origin + "\n"; if (cal.getInvertY()) s += "Inverted y coordinates\n"; Overlay overlay = imp.getOverlay(); if (overlay != null) { String hidden = imp.getHideOverlay() ? " (hidden)" : " "; int n = overlay.size(); String elements = n == 1 ? " element" : " elements"; s += "Overlay: " + n + elements + (imp.getHideOverlay() ? " (hidden)" : "") + "\n"; } else s += "No overlay\n"; Roi roi = imp.getRoi(); if (roi == null) { if (cal.calibrated()) s += " \n"; s += "No selection\n"; } else if (roi instanceof EllipseRoi) { s += "\nElliptical selection\n"; double[] p = ((EllipseRoi) roi).getParams(); double dx = p[2] - p[0]; double dy = p[3] - p[1]; double major = Math.sqrt(dx * dx + dy * dy); s += " Major: " + IJ.d2s(major, 2) + "\n"; s += " Minor: " + IJ.d2s(major * p[4], 2) + "\n"; s += " X1: " + IJ.d2s(p[0], 2) + "\n"; s += " Y1: " + IJ.d2s(p[1], 2) + "\n"; s += " X2: " + IJ.d2s(p[2], 2) + "\n"; s += " Y2: " + IJ.d2s(p[3], 2) + "\n"; s += " Aspect ratio: " + IJ.d2s(p[4], 2) + "\n"; } else { s += " \n"; s += roi.getTypeAsString() + " Selection"; String points = null; if (roi instanceof PointRoi) { int npoints = ((PolygonRoi) roi).getNCoordinates(); String suffix = npoints > 1 ? "s)" : ")"; points = " (" + npoints + " point" + suffix; } String name = roi.getName(); if (name != null) { s += " (\"" + name + "\")"; if (points != null) s += "\n " + points; } else if (points != null) s += points; s += "\n"; Rectangle r = roi.getBounds(); if (roi instanceof Line) { Line line = (Line) roi; s += " X1: " + IJ.d2s(line.x1d * cal.pixelWidth) + "\n"; s += " Y1: " + IJ.d2s(yy(line.y1d, imp) * cal.pixelHeight) + "\n"; s += " X2: " + IJ.d2s(line.x2d * cal.pixelWidth) + "\n"; s += " Y2: " + IJ.d2s(yy(line.y2d, imp) * cal.pixelHeight) + "\n"; } else if (cal.scaled()) { s += " X: " + IJ.d2s(cal.getX(r.x)) + " (" + r.x + ")\n"; s += " Y: " + IJ.d2s(cal.getY(r.y, imp.getHeight())) + " (" + r.y + ")\n"; s += " Width: " + IJ.d2s(r.width * cal.pixelWidth) + " (" + r.width + ")\n"; s += " Height: " + IJ.d2s(r.height * cal.pixelHeight) + " (" + r.height + ")\n"; } else { s += " X: " + r.x + "\n"; s += " Y: " + yy(r.y, imp) + "\n"; s += " Width: " + r.width + "\n"; s += " Height: " + r.height + "\n"; } } return s; }
/** Ask for parameters and then execute. */ public void run(String arg) { // 1 - Obtain the currently active image: ImagePlus imp = IJ.getImage(); if (null == imp) { IJ.showMessage("There must be at least one image open"); return; } if (imp.getBitDepth() != 8) { IJ.showMessage("Error", "Only 8-bit images are supported"); return; } // 2 - Ask for parameters: GenericDialog gd = new GenericDialog("Auto Local Threshold"); String[] methods = { "Try all", "Bernsen", "Contrast", "Mean", "Median", "MidGrey", "Niblack", "Otsu", "Phansalkar", "Sauvola" }; gd.addMessage("Auto Local Threshold v1.5"); gd.addChoice("Method", methods, methods[0]); gd.addNumericField("Radius", 15, 0); gd.addMessage("Special paramters (if different from default)"); gd.addNumericField("Parameter_1", 0, 0); gd.addNumericField("Parameter_2", 0, 0); gd.addCheckbox("White objects on black background", true); if (imp.getStackSize() > 1) { gd.addCheckbox("Stack", false); } gd.addMessage("Thresholded result is always shown in white [255]."); gd.showDialog(); if (gd.wasCanceled()) return; // 3 - Retrieve parameters from the dialog String myMethod = gd.getNextChoice(); int radius = (int) gd.getNextNumber(); double par1 = (double) gd.getNextNumber(); double par2 = (double) gd.getNextNumber(); boolean doIwhite = gd.getNextBoolean(); boolean doIstack = false; int stackSize = imp.getStackSize(); if (stackSize > 1) doIstack = gd.getNextBoolean(); // 4 - Execute! // long start = System.currentTimeMillis(); if (myMethod.equals("Try all")) { ImageProcessor ip = imp.getProcessor(); int xe = ip.getWidth(); int ye = ip.getHeight(); int ml = methods.length; ImagePlus imp2, imp3; ImageStack tstack = null, stackNew; if (stackSize > 1 && doIstack) { boolean doItAnyway = true; if (stackSize > 25) { YesNoCancelDialog d = new YesNoCancelDialog( IJ.getInstance(), "Auto Local Threshold", "You might run out of memory.\n \nDisplay " + stackSize + " slices?\n \n \'No\' will process without display and\noutput results to the log window."); if (!d.yesPressed()) { // doIlog=true; //will show in the log window doItAnyway = false; } if (d.cancelPressed()) return; } for (int j = 1; j <= stackSize; j++) { imp.setSlice(j); ip = imp.getProcessor(); tstack = new ImageStack(xe, ye); for (int k = 1; k < ml; k++) tstack.addSlice(methods[k], ip.duplicate()); imp2 = new ImagePlus("Auto Threshold", tstack); imp2.updateAndDraw(); for (int k = 1; k < ml; k++) { imp2.setSlice(k); Object[] result = exec(imp2, methods[k], radius, par1, par2, doIwhite); } // if (doItAnyway){ CanvasResizer cr = new CanvasResizer(); stackNew = cr.expandStack(tstack, (xe + 2), (ye + 18), 1, 1); imp3 = new ImagePlus("Auto Threshold", stackNew); imp3.updateAndDraw(); MontageMaker mm = new MontageMaker(); mm.makeMontage(imp3, 3, 3, 1.0, 1, (ml - 1), 1, 0, true); // 3 columns and 3 rows } imp.setSlice(1); // if (doItAnyway) IJ.run("Images to Stack", "method=[Copy (center)] title=Montage"); return; } else { // single image try all tstack = new ImageStack(xe, ye); for (int k = 1; k < ml; k++) tstack.addSlice(methods[k], ip.duplicate()); imp2 = new ImagePlus("Auto Threshold", tstack); imp2.updateAndDraw(); for (int k = 1; k < ml; k++) { imp2.setSlice(k); // IJ.log("analyzing slice with "+methods[k]); Object[] result = exec(imp2, methods[k], radius, par1, par2, doIwhite); } // imp2.setSlice(1); CanvasResizer cr = new CanvasResizer(); stackNew = cr.expandStack(tstack, (xe + 2), (ye + 18), 1, 1); imp3 = new ImagePlus("Auto Threshold", stackNew); imp3.updateAndDraw(); MontageMaker mm = new MontageMaker(); mm.makeMontage(imp3, 3, 3, 1.0, 1, (ml - 1), 1, 0, true); return; } } else { // selected a method if (stackSize > 1 && doIstack) { // whole stack // if (doIstackHistogram) {// one global histogram // Object[] result = exec(imp, myMethod, noWhite, noBlack, doIwhite, doIset, doIlog, // doIstackHistogram ); // } // else{ // slice by slice for (int k = 1; k <= stackSize; k++) { imp.setSlice(k); Object[] result = exec(imp, myMethod, radius, par1, par2, doIwhite); } // } imp.setSlice(1); } else { // just one slice Object[] result = exec(imp, myMethod, radius, par1, par2, doIwhite); } // 5 - If all went well, show the image: // not needed here as the source image is binarised } }
public BandAdjuster() { super("Threshold Colour"); if (instance != null) { instance.toFront(); return; } imp = WindowManager.getCurrentImage(); if (imp == null) { IJ.beep(); IJ.showStatus("No image"); return; } IJ.run("Select None"); thread = new Thread(this, "BandAdjuster"); WindowManager.addWindow(this); instance = this; IJ.register(PasteController.class); ij = IJ.getInstance(); Font font = new Font("SansSerif", Font.PLAIN, 10); GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); setLayout(gridbag); int y = 0; c.gridx = 0; c.gridy = y; c.gridwidth = 1; c.weightx = 0; c.insets = new Insets(5, 0, 0, 0); labelh = new Label("Hue", Label.CENTER); add(labelh, c); c.gridx = 1; c.gridy = y++; c.gridwidth = 1; c.weightx = 0; c.insets = new Insets(7, 0, 0, 0); labelf = new Label("Filter type", Label.RIGHT); add(labelf, c); // plot c.gridx = 0; c.gridy = y; c.gridwidth = 1; c.fill = c.BOTH; c.anchor = c.CENTER; c.insets = new Insets(0, 5, 0, 0); add(plot, c); // checkboxes panelh = new Panel(); filterTypeH = new CheckboxGroup(); bandPassH = new Checkbox("Pass"); bandPassH.setCheckboxGroup(filterTypeH); bandPassH.addItemListener(this); panelh.add(bandPassH); bandStopH = new Checkbox("Stop"); bandStopH.setCheckboxGroup(filterTypeH); bandStopH.addItemListener(this); panelh.add(bandStopH); bandPassH.setState(true); c.gridx = 1; c.gridy = y++; c.gridwidth = 2; c.insets = new Insets(5, 0, 0, 0); add(panelh, c); // minHue slider minSlider = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, sliderRange); c.gridx = 0; c.gridy = y++; c.gridwidth = 1; c.weightx = IJ.isMacintosh() ? 90 : 100; c.fill = c.HORIZONTAL; c.insets = new Insets(5, 5, 0, 0); add(minSlider, c); minSlider.addAdjustmentListener(this); minSlider.setUnitIncrement(1); // minHue slider label c.gridx = 1; c.gridwidth = 1; c.weightx = IJ.isMacintosh() ? 10 : 0; c.insets = new Insets(5, 0, 0, 0); label1 = new Label(" ", Label.LEFT); label1.setFont(font); add(label1, c); // maxHue sliderHue maxSlider = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, sliderRange); c.gridx = 0; c.gridy = y; c.gridwidth = 1; c.weightx = 100; c.insets = new Insets(5, 5, 0, 0); add(maxSlider, c); maxSlider.addAdjustmentListener(this); maxSlider.setUnitIncrement(1); // maxHue slider label c.gridx = 1; c.gridwidth = 1; c.gridy = y++; c.weightx = 0; c.insets = new Insets(5, 0, 0, 0); label2 = new Label(" ", Label.LEFT); label2.setFont(font); add(label2, c); // ===== c.gridx = 0; c.gridy = y++; c.gridwidth = 1; c.weightx = 0; c.insets = new Insets(10, 0, 0, 0); labels = new Label("Saturation", Label.CENTER); add(labels, c); // plot c.gridx = 0; c.gridy = y; c.gridwidth = 1; c.fill = c.BOTH; c.anchor = c.CENTER; c.insets = new Insets(0, 5, 0, 0); add(splot, c); // checkboxes panels = new Panel(); filterTypeS = new CheckboxGroup(); bandPassS = new Checkbox("Pass"); bandPassS.setCheckboxGroup(filterTypeS); bandPassS.addItemListener(this); panels.add(bandPassS); bandStopS = new Checkbox("Stop"); bandStopS.setCheckboxGroup(filterTypeS); bandStopS.addItemListener(this); panels.add(bandStopS); bandPassS.setState(true); c.gridx = 1; c.gridy = y++; c.gridwidth = 2; c.insets = new Insets(5, 0, 0, 0); add(panels, c); // minSat slider minSlider2 = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, sliderRange); c.gridx = 0; c.gridy = y++; c.gridwidth = 1; c.weightx = IJ.isMacintosh() ? 90 : 100; c.fill = c.HORIZONTAL; c.insets = new Insets(5, 5, 0, 0); add(minSlider2, c); minSlider2.addAdjustmentListener(this); minSlider2.setUnitIncrement(1); // minSat slider label c.gridx = 1; c.gridwidth = 1; c.weightx = IJ.isMacintosh() ? 10 : 0; c.insets = new Insets(5, 0, 0, 0); label3 = new Label(" ", Label.LEFT); label3.setFont(font); add(label3, c); // maxSat slider maxSlider2 = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, sliderRange); c.gridx = 0; c.gridy = y++; c.gridwidth = 1; c.weightx = 100; c.insets = new Insets(5, 5, 0, 0); add(maxSlider2, c); maxSlider2.addAdjustmentListener(this); maxSlider2.setUnitIncrement(1); // maxSat slider label c.gridx = 1; c.gridwidth = 1; c.weightx = 0; c.insets = new Insets(5, 0, 0, 0); label4 = new Label(" ", Label.LEFT); label4.setFont(font); add(label4, c); // ===== c.gridx = 0; c.gridwidth = 1; c.gridy = y++; c.weightx = 0; c.insets = new Insets(10, 0, 0, 0); labelb = new Label("Brightness", Label.CENTER); add(labelb, c); c.gridx = 0; c.gridwidth = 1; c.gridy = y; c.fill = c.BOTH; c.anchor = c.CENTER; c.insets = new Insets(0, 5, 0, 0); add(bplot, c); // checkboxes panelb = new Panel(); filterTypeB = new CheckboxGroup(); bandPassB = new Checkbox("Pass"); bandPassB.setCheckboxGroup(filterTypeB); bandPassB.addItemListener(this); panelb.add(bandPassB); bandStopB = new Checkbox("Stop"); bandStopB.setCheckboxGroup(filterTypeB); bandStopB.addItemListener(this); panelb.add(bandStopB); bandPassB.setState(true); c.gridx = 1; c.gridy = y++; c.gridwidth = 2; c.insets = new Insets(5, 0, 0, 0); add(panelb, c); // minBri slider minSlider3 = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, sliderRange); c.gridx = 0; c.gridy = y++; c.gridwidth = 1; c.weightx = IJ.isMacintosh() ? 90 : 100; c.fill = c.HORIZONTAL; c.insets = new Insets(5, 5, 0, 0); add(minSlider3, c); minSlider3.addAdjustmentListener(this); minSlider3.setUnitIncrement(1); // minBri slider label c.gridx = 1; c.gridwidth = 1; c.weightx = IJ.isMacintosh() ? 10 : 0; c.insets = new Insets(5, 0, 0, 0); label5 = new Label(" ", Label.LEFT); label5.setFont(font); add(label5, c); // maxBri slider maxSlider3 = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, sliderRange); c.gridx = 0; c.gridy = y++; c.gridwidth = 1; c.weightx = 100; c.insets = new Insets(5, 5, 0, 0); add(maxSlider3, c); maxSlider3.addAdjustmentListener(this); maxSlider3.setUnitIncrement(1); // maxBri slider label c.gridx = 1; c.gridwidth = 1; c.weightx = 0; c.insets = new Insets(5, 0, 0, 0); label6 = new Label(" ", Label.LEFT); label6.setFont(font); add(label6, c); // ===== panelt = new Panel(); threshold = new Checkbox("Threshold"); threshold.addItemListener(this); panelt.add(threshold); invert = new Checkbox("Invert"); invert.addItemListener(this); panelt.add(invert); c.gridx = 0; c.gridy = y++; c.gridwidth = 2; c.insets = new Insets(0, 0, 0, 0); add(panelt, c); // buttons panel = new Panel(); // panel.setLayout(new GridLayout(2, 2, 0, 0)); originalB = new Button("Original"); originalB.setEnabled(false); originalB.addActionListener(this); originalB.addKeyListener(ij); panel.add(originalB); filteredB = new Button("Filtered"); filteredB.setEnabled(false); filteredB.addActionListener(this); filteredB.addKeyListener(ij); panel.add(filteredB); stackB = new Button("Stack"); stackB.addActionListener(this); stackB.addKeyListener(ij); panel.add(stackB); helpB = new Button("Help"); helpB.addActionListener(this); helpB.addKeyListener(ij); panel.add(helpB); c.gridx = 0; c.gridy = y++; c.gridwidth = 2; c.insets = new Insets(0, 0, 0, 0); add(panel, c); panelMode = new Panel(); sampleB = new Button("Sample"); sampleB.addActionListener(this); sampleB.addKeyListener(ij); panelMode.add(sampleB); colourMode = new CheckboxGroup(); hsb = new Checkbox("HSB"); hsb.setCheckboxGroup(colourMode); hsb.addItemListener(this); panelMode.add(hsb); hsb.setState(true); rgb = new Checkbox("RGB"); rgb.setCheckboxGroup(colourMode); rgb.addItemListener(this); panelMode.add(rgb); c.gridx = 0; c.gridy = y++; c.gridwidth = 2; c.insets = new Insets(0, 0, 0, 0); add(panelMode, c); addKeyListener(ij); // ImageJ handles keyboard shortcuts pack(); GUI.center(this); setVisible(true); ip = setup(imp); if (ip == null) { imp.unlock(); IJ.beep(); IJ.showStatus("RGB image cannot be thresholded"); return; } thread.start(); }
/*------------------------------------------------------------------*/ public class Differentials_ implements PlugIn { /* begin class Differentials_ */ /*..................................................................*/ /* Global-scope variables */ /*..................................................................*/ static final int GRADIENT_MAGNITUDE = 1; static final int GRADIENT_DIRECTION = 2; static final int LAPLACIAN = 3; static final int LARGEST_HESSIAN = 4; static final int SMALLEST_HESSIAN = 5; static final int HESSIAN_ORIENTATION = 6; private final double FLT_EPSILON = (double) Float.intBitsToFloat((int) 0x33FFFFFF); private ImagePlus imp = null; private ProgressBar progressBar = IJ.getInstance().getProgressBar(); private long lastTime = System.currentTimeMillis(); private int completed = 1; private int processDuration = 1; private static int operation = LAPLACIAN; private int stackSize = 1; private boolean cancel = false; /*..................................................................*/ /* Public methods */ /*..................................................................*/ /*------------------------------------------------------------------*/ public void getCrossHessian(ImageProcessor ip, double tolerance) { getHorizontalGradient(ip, tolerance); getVerticalGradient(ip, tolerance); } /* end getCrossHessian */ /*------------------------------------------------------------------*/ public void getHorizontalGradient(ImageProcessor ip, double tolerance) { if (!(ip.getPixels() instanceof float[])) { throw new IllegalArgumentException("Float image required"); } float[] floatPixels = (float[]) ip.getPixels(); int width = ip.getWidth(); int height = ip.getHeight(); double line[] = new double[width]; for (int y = 0; (y < height); y++) { getRow(ip, y, line); getSplineInterpolationCoefficients(line, tolerance); getGradient(line); putRow(ip, y, line); stepProgressBar(); } } /* end getHorizontalGradient */ /*------------------------------------------------------------------*/ public void getHorizontalHessian(ImageProcessor ip, double tolerance) { if (!(ip.getPixels() instanceof float[])) { throw new IllegalArgumentException("Float image required"); } float[] floatPixels = (float[]) ip.getPixels(); int width = ip.getWidth(); int height = ip.getHeight(); double line[] = new double[width]; for (int y = 0; (y < height); y++) { getRow(ip, y, line); getSplineInterpolationCoefficients(line, tolerance); getHessian(line); putRow(ip, y, line); stepProgressBar(); } } /* end getHorizontalHessian */ /*------------------------------------------------------------------*/ public void getVerticalGradient(ImageProcessor ip, double tolerance) { if (!(ip.getPixels() instanceof float[])) { throw new IllegalArgumentException("Float image required"); } float[] floatPixels = (float[]) ip.getPixels(); int width = ip.getWidth(); int height = ip.getHeight(); double line[] = new double[height]; for (int x = 0; (x < width); x++) { getColumn(ip, x, line); getSplineInterpolationCoefficients(line, tolerance); getGradient(line); putColumn(ip, x, line); stepProgressBar(); } } /* end getVerticalGradient */ /*------------------------------------------------------------------*/ public void getVerticalHessian(ImageProcessor ip, double tolerance) { if (!(ip.getPixels() instanceof float[])) { throw new IllegalArgumentException("Float image required"); } float[] floatPixels = (float[]) ip.getPixels(); int width = ip.getWidth(); int height = ip.getHeight(); double line[] = new double[height]; for (int x = 0; (x < width); x++) { getColumn(ip, x, line); getSplineInterpolationCoefficients(line, tolerance); getHessian(line); putColumn(ip, x, line); stepProgressBar(); } } /* end getVerticalHessian */ /*------------------------------------------------------------------*/ public void run(String arg) { ImagePlus imp = WindowManager.getCurrentImage(); this.imp = imp; if (imp == null) { IJ.noImage(); return; } if ((1 < imp.getStackSize()) && (imp.getType() == imp.COLOR_256)) { IJ.error("Stack of color images not supported (use grayscale)"); return; } if (1 < imp.getStackSize()) { if (imp.getStack().isRGB()) { IJ.error("RGB color images not supported (use grayscale)"); return; } } if (1 < imp.getStackSize()) { if (imp.getStack().isHSB()) { IJ.error("HSB color images not supported (use grayscale)"); return; } } if (imp.getType() == imp.COLOR_256) { IJ.error("Indexed color images not supported (use grayscale)"); return; } if (imp.getType() == imp.COLOR_RGB) { IJ.error("Color images not supported (use grayscale)"); return; } differentialsDialog dialog = new differentialsDialog(IJ.getInstance(), "Differentials", true, operation); GUI.center(dialog); dialog.setVisible(true); cancel = dialog.getCancel(); operation = dialog.getOperation(); dialog.dispose(); if (cancel) { return; } imp.startTiming(); if (1 < imp.getStackSize()) { if (!(imp.getProcessor().getPixels() instanceof float[])) { new StackConverter(imp).convertToGray32(); } } else { if (!(imp.getProcessor().getPixels() instanceof float[])) { new ImageConverter(imp).convertToGray32(); } } ImageStack stack = imp.getStack(); stackSize = stack.getSize(); Undo.reset(); setupProgressBar(); resetProgressBar(); for (int i = 1; (i <= stackSize); i++) { ImageProcessor ip = stack.getProcessor(i); doIt(ip); imp.getProcessor().resetMinAndMax(); imp.setSlice(i); imp.updateAndRepaintWindow(); } imp.getProcessor().resetMinAndMax(); imp.setSlice(1); imp.updateAndRepaintWindow(); cleanUpProgressBar(); IJ.showTime(imp, imp.getStartTime(), "Differentials: "); ImageWindow win = imp.getWindow(); if (win != null) { win.running = false; } } /* end run */ /*..................................................................*/ /* Private methods */ /*..................................................................*/ /*------------------------------------------------------------------*/ void antiSymmetricFirMirrorOnBounds(double[] h, double[] c, double[] s) { if (h.length != 2) { throw new IndexOutOfBoundsException("The half-length filter size should be 2"); } if (h[0] != 0.0) { throw new IllegalArgumentException("Antisymmetry violation (should have h[0]=0.0)"); } if (c.length != s.length) { throw new IndexOutOfBoundsException("Incompatible size"); } if (2 <= c.length) { s[0] = 0.0; for (int i = 1; (i < (s.length - 1)); i++) { s[i] = h[1] * (c[i + 1] - c[i - 1]); } s[s.length - 1] = 0.0; } else { if (c.length == 1) { s[0] = 0.0; } else { throw new NegativeArraySizeException("Invalid length of data"); } } } /* end antiSymmetricFirMirrorOnBounds */ /*------------------------------------------------------------------*/ void cleanUpProgressBar() { completed = 0; progressBar.show(2.0); } /* end cleanUpProgressBar */ /*------------------------------------------------------------------*/ void doIt(ImageProcessor ip) { int width = ip.getWidth(); int height = ip.getHeight(); double hLine[] = new double[width]; double vLine[] = new double[height]; if (!(ip.getPixels() instanceof float[])) { throw new IllegalArgumentException("Float image required"); } switch (operation) { case GRADIENT_MAGNITUDE: { ImageProcessor h = ip.duplicate(); ImageProcessor v = ip.duplicate(); float[] floatPixels = (float[]) ip.getPixels(); float[] floatPixelsH = (float[]) h.getPixels(); float[] floatPixelsV = (float[]) v.getPixels(); getHorizontalGradient(h, FLT_EPSILON); getVerticalGradient(v, FLT_EPSILON); for (int y = 0, k = 0; (y < height); y++) { for (int x = 0; (x < width); x++, k++) { floatPixels[k] = (float) Math.sqrt( floatPixelsH[k] * floatPixelsH[k] + floatPixelsV[k] * floatPixelsV[k]); } stepProgressBar(); } } break; case GRADIENT_DIRECTION: { ImageProcessor h = ip.duplicate(); ImageProcessor v = ip.duplicate(); float[] floatPixels = (float[]) ip.getPixels(); float[] floatPixelsH = (float[]) h.getPixels(); float[] floatPixelsV = (float[]) v.getPixels(); getHorizontalGradient(h, FLT_EPSILON); getVerticalGradient(v, FLT_EPSILON); for (int y = 0, k = 0; (y < height); y++) { for (int x = 0; (x < width); x++, k++) { floatPixels[k] = (float) Math.atan2(floatPixelsH[k], floatPixelsV[k]); } stepProgressBar(); } } break; case LAPLACIAN: { ImageProcessor hh = ip.duplicate(); ImageProcessor vv = ip.duplicate(); float[] floatPixels = (float[]) ip.getPixels(); float[] floatPixelsHH = (float[]) hh.getPixels(); float[] floatPixelsVV = (float[]) vv.getPixels(); getHorizontalHessian(hh, FLT_EPSILON); getVerticalHessian(vv, FLT_EPSILON); for (int y = 0, k = 0; (y < height); y++) { for (int x = 0; (x < width); x++, k++) { floatPixels[k] = (float) (floatPixelsHH[k] + floatPixelsVV[k]); } stepProgressBar(); } } break; case LARGEST_HESSIAN: { ImageProcessor hh = ip.duplicate(); ImageProcessor vv = ip.duplicate(); ImageProcessor hv = ip.duplicate(); float[] floatPixels = (float[]) ip.getPixels(); float[] floatPixelsHH = (float[]) hh.getPixels(); float[] floatPixelsVV = (float[]) vv.getPixels(); float[] floatPixelsHV = (float[]) hv.getPixels(); getHorizontalHessian(hh, FLT_EPSILON); getVerticalHessian(vv, FLT_EPSILON); getCrossHessian(hv, FLT_EPSILON); for (int y = 0, k = 0; (y < height); y++) { for (int x = 0; (x < width); x++, k++) { floatPixels[k] = (float) (0.5 * (floatPixelsHH[k] + floatPixelsVV[k] + Math.sqrt( 4.0 * floatPixelsHV[k] * floatPixelsHV[k] + (floatPixelsHH[k] - floatPixelsVV[k]) * (floatPixelsHH[k] - floatPixelsVV[k])))); } stepProgressBar(); } } break; case SMALLEST_HESSIAN: { ImageProcessor hh = ip.duplicate(); ImageProcessor vv = ip.duplicate(); ImageProcessor hv = ip.duplicate(); float[] floatPixels = (float[]) ip.getPixels(); float[] floatPixelsHH = (float[]) hh.getPixels(); float[] floatPixelsVV = (float[]) vv.getPixels(); float[] floatPixelsHV = (float[]) hv.getPixels(); getHorizontalHessian(hh, FLT_EPSILON); getVerticalHessian(vv, FLT_EPSILON); getCrossHessian(hv, FLT_EPSILON); for (int y = 0, k = 0; (y < height); y++) { for (int x = 0; (x < width); x++, k++) { floatPixels[k] = (float) (0.5 * (floatPixelsHH[k] + floatPixelsVV[k] - Math.sqrt( 4.0 * floatPixelsHV[k] * floatPixelsHV[k] + (floatPixelsHH[k] - floatPixelsVV[k]) * (floatPixelsHH[k] - floatPixelsVV[k])))); } stepProgressBar(); } } break; case HESSIAN_ORIENTATION: { ImageProcessor hh = ip.duplicate(); ImageProcessor vv = ip.duplicate(); ImageProcessor hv = ip.duplicate(); float[] floatPixels = (float[]) ip.getPixels(); float[] floatPixelsHH = (float[]) hh.getPixels(); float[] floatPixelsVV = (float[]) vv.getPixels(); float[] floatPixelsHV = (float[]) hv.getPixels(); getHorizontalHessian(hh, FLT_EPSILON); getVerticalHessian(vv, FLT_EPSILON); getCrossHessian(hv, FLT_EPSILON); for (int y = 0, k = 0; (y < height); y++) { for (int x = 0; (x < width); x++, k++) { if (floatPixelsHV[k] < 0.0) { floatPixels[k] = (float) (-0.5 * Math.acos( (floatPixelsHH[k] - floatPixelsVV[k]) / Math.sqrt( 4.0 * floatPixelsHV[k] * floatPixelsHV[k] + (floatPixelsHH[k] - floatPixelsVV[k]) * (floatPixelsHH[k] - floatPixelsVV[k])))); } else { floatPixels[k] = (float) (0.5 * Math.acos( (floatPixelsHH[k] - floatPixelsVV[k]) / Math.sqrt( 4.0 * floatPixelsHV[k] * floatPixelsHV[k] + (floatPixelsHH[k] - floatPixelsVV[k]) * (floatPixelsHH[k] - floatPixelsVV[k])))); } } stepProgressBar(); } } break; default: throw new IllegalArgumentException("Invalid operation"); } ip.resetMinAndMax(); imp.updateAndDraw(); } /* end doIt */ /*------------------------------------------------------------------*/ void getColumn(ImageProcessor ip, int x, double[] column) { int width = ip.getWidth(); if (ip.getHeight() != column.length) { throw new IndexOutOfBoundsException("Incoherent array sizes"); } if (ip.getPixels() instanceof float[]) { float[] floatPixels = (float[]) ip.getPixels(); for (int i = 0; (i < column.length); i++) { column[i] = (double) floatPixels[x]; x += width; } } else { throw new IllegalArgumentException("Float image required"); } } /* end getColumn */ /*------------------------------------------------------------------*/ void getGradient(double[] c) { double h[] = {0.0, -1.0 / 2.0}; double s[] = new double[c.length]; antiSymmetricFirMirrorOnBounds(h, c, s); System.arraycopy(s, 0, c, 0, s.length); } /* end getGradient */ /*------------------------------------------------------------------*/ void getHessian(double[] c) { double h[] = {-2.0, 1.0}; double s[] = new double[c.length]; symmetricFirMirrorOnBounds(h, c, s); System.arraycopy(s, 0, c, 0, s.length); } /* end getHessian */ /*------------------------------------------------------------------*/ double getInitialAntiCausalCoefficientMirrorOnBounds(double[] c, double z, double tolerance) { return ((z * c[c.length - 2] + c[c.length - 1]) * z / (z * z - 1.0)); } /* end getInitialAntiCausalCoefficientMirrorOnBounds */ /*------------------------------------------------------------------*/ double getInitialCausalCoefficientMirrorOnBounds(double[] c, double z, double tolerance) { double z1 = z, zn = Math.pow(z, c.length - 1); double sum = c[0] + zn * c[c.length - 1]; int horizon = c.length; if (0.0 < tolerance) { horizon = 2 + (int) (Math.log(tolerance) / Math.log(Math.abs(z))); horizon = (horizon < c.length) ? (horizon) : (c.length); } zn = zn * zn; for (int n = 1; (n < (horizon - 1)); n++) { zn = zn / z; sum = sum + (z1 + zn) * c[n]; z1 = z1 * z; } return (sum / (1.0 - Math.pow(z, 2 * c.length - 2))); } /* end getInitialCausalCoefficientMirrorOnBounds */ /*------------------------------------------------------------------*/ void getRow(ImageProcessor ip, int y, double[] row) { int rowLength = ip.getWidth(); if (rowLength != row.length) { throw new IndexOutOfBoundsException("Incoherent array sizes"); } y *= rowLength; if (ip.getPixels() instanceof float[]) { float[] floatPixels = (float[]) ip.getPixels(); for (int i = 0; (i < rowLength); i++) { row[i] = (double) floatPixels[y++]; } } else { throw new IllegalArgumentException("Float image required"); } } /* end getRow */ /*------------------------------------------------------------------*/ void getSplineInterpolationCoefficients(double[] c, double tolerance) { double z[] = {Math.sqrt(3.0) - 2.0}; double lambda = 1.0; if (c.length == 1) { return; } for (int k = 0; (k < z.length); k++) { lambda = lambda * (1.0 - z[k]) * (1.0 - 1.0 / z[k]); } for (int n = 0; (n < c.length); n++) { c[n] = c[n] * lambda; } for (int k = 0; (k < z.length); k++) { c[0] = getInitialCausalCoefficientMirrorOnBounds(c, z[k], tolerance); for (int n = 1; (n < c.length); n++) { c[n] = c[n] + z[k] * c[n - 1]; } c[c.length - 1] = getInitialAntiCausalCoefficientMirrorOnBounds(c, z[k], tolerance); for (int n = c.length - 2; (0 <= n); n--) { c[n] = z[k] * (c[n + 1] - c[n]); } } } /* end getSplineInterpolationCoefficients */ /*------------------------------------------------------------------*/ void putColumn(ImageProcessor ip, int x, double[] column) { int width = ip.getWidth(); if (ip.getHeight() != column.length) { throw new IndexOutOfBoundsException("Incoherent array sizes"); } if (ip.getPixels() instanceof float[]) { float[] floatPixels = (float[]) ip.getPixels(); for (int i = 0; (i < column.length); i++) { floatPixels[x] = (float) column[i]; x += width; } } else { throw new IllegalArgumentException("Float image required"); } } /* end putColumn */ /*------------------------------------------------------------------*/ void putRow(ImageProcessor ip, int y, double[] row) { int rowLength = ip.getWidth(); if (rowLength != row.length) { throw new IndexOutOfBoundsException("Incoherent array sizes"); } y *= rowLength; if (ip.getPixels() instanceof float[]) { float[] floatPixels = (float[]) ip.getPixels(); for (int i = 0; (i < rowLength); i++) { floatPixels[y++] = (float) row[i]; } } else { throw new IllegalArgumentException("Float image required"); } } /* end putRow */ /*------------------------------------------------------------------*/ void resetProgressBar() { completed = 0; lastTime = System.currentTimeMillis(); progressBar.show(2.0); } /* end resetProgressBar */ /*------------------------------------------------------------------*/ void setupProgressBar() { int height = imp.getHeight(); int width = imp.getWidth(); completed = 0; lastTime = System.currentTimeMillis(); switch (operation) { case GRADIENT_MAGNITUDE: processDuration = stackSize * (width + 2 * height); break; case GRADIENT_DIRECTION: processDuration = stackSize * (width + 2 * height); break; case LAPLACIAN: processDuration = stackSize * (width + 2 * height); break; case LARGEST_HESSIAN: processDuration = stackSize * (2 * width + 3 * height); break; case SMALLEST_HESSIAN: processDuration = stackSize * (2 * width + 3 * height); break; case HESSIAN_ORIENTATION: processDuration = stackSize * (2 * width + 3 * height); break; default: throw new IllegalArgumentException("Invalid operation"); } } /* end setupProgressBar */ /*------------------------------------------------------------------*/ void stepProgressBar() { long timeStamp = System.currentTimeMillis(); completed = completed + 1; if (50L < (timeStamp - lastTime)) { lastTime = timeStamp; progressBar.show((double) completed / (double) processDuration); } } /* end stepProgressBar */ /*------------------------------------------------------------------*/ void symmetricFirMirrorOnBounds(double[] h, double[] c, double[] s) { if (h.length != 2) { throw new IndexOutOfBoundsException("The half-length filter size should be 2"); } if (c.length != s.length) { throw new IndexOutOfBoundsException("Incompatible size"); } if (2 <= c.length) { s[0] = h[0] * c[0] + 2.0 * h[1] * c[1]; for (int i = 1; (i < (s.length - 1)); i++) { s[i] = h[0] * c[i] + h[1] * (c[i - 1] + c[i + 1]); } s[s.length - 1] = h[0] * c[c.length - 1] + 2.0 * h[1] * c[c.length - 2]; } else { switch (c.length) { case 1: s[0] = (h[0] + 2.0 * h[1]) * c[0]; break; default: throw new NegativeArraySizeException("Invalid length of data"); } } } /* end symmetricFirMirrorOnBounds */ } /* end class Differentials_ */
/*------------------------------------------------------------------*/ public void run(String arg) { ImagePlus imp = WindowManager.getCurrentImage(); this.imp = imp; if (imp == null) { IJ.noImage(); return; } if ((1 < imp.getStackSize()) && (imp.getType() == imp.COLOR_256)) { IJ.error("Stack of color images not supported (use grayscale)"); return; } if (1 < imp.getStackSize()) { if (imp.getStack().isRGB()) { IJ.error("RGB color images not supported (use grayscale)"); return; } } if (1 < imp.getStackSize()) { if (imp.getStack().isHSB()) { IJ.error("HSB color images not supported (use grayscale)"); return; } } if (imp.getType() == imp.COLOR_256) { IJ.error("Indexed color images not supported (use grayscale)"); return; } if (imp.getType() == imp.COLOR_RGB) { IJ.error("Color images not supported (use grayscale)"); return; } differentialsDialog dialog = new differentialsDialog(IJ.getInstance(), "Differentials", true, operation); GUI.center(dialog); dialog.setVisible(true); cancel = dialog.getCancel(); operation = dialog.getOperation(); dialog.dispose(); if (cancel) { return; } imp.startTiming(); if (1 < imp.getStackSize()) { if (!(imp.getProcessor().getPixels() instanceof float[])) { new StackConverter(imp).convertToGray32(); } } else { if (!(imp.getProcessor().getPixels() instanceof float[])) { new ImageConverter(imp).convertToGray32(); } } ImageStack stack = imp.getStack(); stackSize = stack.getSize(); Undo.reset(); setupProgressBar(); resetProgressBar(); for (int i = 1; (i <= stackSize); i++) { ImageProcessor ip = stack.getProcessor(i); doIt(ip); imp.getProcessor().resetMinAndMax(); imp.setSlice(i); imp.updateAndRepaintWindow(); } imp.getProcessor().resetMinAndMax(); imp.setSlice(1); imp.updateAndRepaintWindow(); cleanUpProgressBar(); IJ.showTime(imp, imp.getStartTime(), "Differentials: "); ImageWindow win = imp.getWindow(); if (win != null) { win.running = false; } } /* end run */