void createMaskFromThreshold(ImagePlus imp) { ImageProcessor ip = imp.getProcessor(); if (ip.getMinThreshold() == ImageProcessor.NO_THRESHOLD) { IJ.error("Create Mask", "Area selection or thresholded image required"); return; } double t1 = ip.getMinThreshold(); double t2 = ip.getMaxThreshold(); IJ.run("Duplicate...", "title=mask"); ImagePlus imp2 = WindowManager.getCurrentImage(); ImageProcessor ip2 = imp2.getProcessor(); ip2.setThreshold(t1, t2, ImageProcessor.NO_LUT_UPDATE); IJ.run("Convert to Mask"); }
void runMacro(String arg) { Roi roi = imp.getRoi(); if (IJ.macroRunning()) { String options = Macro.getOptions(); if (options != null && (options.indexOf("grid=") != -1 || options.indexOf("interpolat") != -1)) { IJ.run("Rotate... ", options); // run Image>Transform>Rotate return; } } if (roi == null) { noRoi("Rotate>Selection"); return; } roi = (Roi) roi.clone(); if (arg.equals("rotate")) { double d = Tools.parseDouble(angle); if (Double.isNaN(d)) angle = "15"; String value = IJ.runMacroFile("ij.jar:RotateSelection", angle); if (value != null) angle = value; } else if (arg.equals("enlarge")) { String value = IJ.runMacroFile("ij.jar:EnlargeSelection", enlarge); if (value != null) enlarge = value; Roi.previousRoi = roi; } }
private void openDirectory(File f, String path) { if (path == null) return; if (!(path.endsWith(File.separator) || path.endsWith("/"))) path += File.separator; String[] names = f.list(); names = (new FolderOpener()).trimFileList(names); if (names == null) return; String msg = "Open all " + names.length + " images in \"" + f.getName() + "\" as a stack?"; GenericDialog gd = new GenericDialog("Open Folder"); gd.setInsets(10, 5, 0); gd.addMessage(msg); gd.setInsets(15, 35, 0); gd.addCheckbox("Convert to RGB", convertToRGB); gd.setInsets(0, 35, 0); gd.addCheckbox("Use Virtual Stack", virtualStack); gd.enableYesNoCancel(); gd.showDialog(); if (gd.wasCanceled()) return; if (gd.wasOKed()) { convertToRGB = gd.getNextBoolean(); virtualStack = gd.getNextBoolean(); String options = " sort"; if (convertToRGB) options += " convert_to_rgb"; if (virtualStack) options += " use"; IJ.run("Image Sequence...", "open=[" + path + "]" + options); DirectoryChooser.setDefaultDirectory(path); } else { for (int k = 0; k < names.length; k++) { IJ.redirectErrorMessages(); if (!names[k].startsWith(".")) (new Opener()).open(path + names[k]); } } IJ.register(DragAndDrop.class); }
/** * Saves statistics for one particle in a results table. This is a method subclasses may want to * override. */ protected void saveResults(ImageStatistics stats, Roi roi) { analyzer.saveResults(stats, roi); if (recordStarts) { rt.addValue("XStart", stats.xstart); rt.addValue("YStart", stats.ystart); } if (addToManager) { if (roiManager == null) { if (Macro.getOptions() != null && Interpreter.isBatchMode()) roiManager = Interpreter.getBatchModeRoiManager(); if (roiManager == null) { Frame frame = WindowManager.getFrame("ROI Manager"); if (frame == null) IJ.run("ROI Manager..."); frame = WindowManager.getFrame("ROI Manager"); if (frame == null || !(frame instanceof RoiManager)) { addToManager = false; return; } roiManager = (RoiManager) frame; } if (resetCounter) roiManager.runCommand("reset"); } if (imp.getStackSize() > 1) roi.setPosition(imp.getCurrentSlice()); if (lineWidth != 1) roi.setStrokeWidth(lineWidth); roiManager.add(imp, roi, rt.getCounter()); } if (showResults) rt.addResults(); }
void addToRoiManager(ImagePlus imp) { if (IJ.macroRunning() && Interpreter.isBatchModeRoiManager()) IJ.error("run(\"Add to Manager\") may not work in batch mode macros"); Frame frame = WindowManager.getFrame("ROI Manager"); if (frame == null) IJ.run("ROI Manager..."); if (imp == null) return; Roi roi = imp.getRoi(); if (roi == null) return; frame = WindowManager.getFrame("ROI Manager"); if (frame == null || !(frame instanceof RoiManager)) IJ.error("ROI Manager not found"); RoiManager rm = (RoiManager) frame; boolean altDown = IJ.altKeyDown(); IJ.setKeyUp(IJ.ALL_KEYS); if (altDown && !IJ.macroRunning()) IJ.setKeyDown(KeyEvent.VK_SHIFT); if (roi.getState() == Roi.CONSTRUCTING) { // wait (up to 2 sec.) until ROI finished long start = System.currentTimeMillis(); while (true) { IJ.wait(10); if (roi.getState() != Roi.CONSTRUCTING) break; if ((System.currentTimeMillis() - start) > 2000) { IJ.beep(); IJ.error("Add to Manager", "Selection is not complete"); return; } } } rm.runCommand("add"); IJ.setKeyUp(IJ.ALL_KEYS); }
public void run(String arg) { ImagePlus imp = WindowManager.getCurrentImage(); if (imp == null) { IJ.noImage(); return; } ImageStack stack1 = imp.getStack(); String fileName = imp.getTitle(); int endslice = stack1.getSize(); ImagePlus imp2 = duplicateStack(imp); imp2.show(); String duplicateName = imp2.getTitle(); // IJ.showMessage("Box",fileName); ImageStack stack2 = imp2.getStack(); stack1.deleteSlice(1); stack2.deleteSlice(endslice); String calculatorstring = ("image1='" + fileName + "' operation=Subtract image2=" + imp2.getTitle() + " create stack"); IJ.run("Image Calculator...", calculatorstring); ImagePlus imp3 = WindowManager.getCurrentImage(); imp3.setTitle(fileName + " DeltaF up"); imp2.getWindow().close(); imp.getWindow().close(); }
public void mouseWheelMoved(MouseWheelEvent event) { synchronized (this) { int rotation = event.getWheelRotation(); if (hyperStack) { if (rotation > 0) IJ.run(imp, "Next Slice [>]", ""); else if (rotation < 0) IJ.run(imp, "Previous Slice [<]", ""); } else { int slice = imp.getCurrentSlice() + rotation; if (slice < 1) slice = 1; else if (slice > imp.getStack().getSize()) slice = imp.getStack().getSize(); imp.setSlice(slice); imp.updateStatusbarValue(); SyncWindows.setZ(this, slice); } } }
public void run(String arg) { int[] wList = WindowManager.getIDList(); if (wList == null) { IJ.error("No images are open."); return; } double thalf = 0.5; boolean keep; GenericDialog gd = new GenericDialog("Bleach correction"); gd.addNumericField("t½:", thalf, 1); gd.addCheckbox("Keep source stack:", true); gd.showDialog(); if (gd.wasCanceled()) return; long start = System.currentTimeMillis(); thalf = gd.getNextNumber(); keep = gd.getNextBoolean(); if (keep) IJ.run("Duplicate...", "title='Bleach corrected' duplicate"); ImagePlus imp1 = WindowManager.getCurrentImage(); int d1 = imp1.getStackSize(); double v1, v2; int width = imp1.getWidth(); int height = imp1.getHeight(); ImageProcessor ip1, ip2, ip3; int slices = imp1.getStackSize(); ImageStack stack1 = imp1.getStack(); ImageStack stack2 = imp1.getStack(); int currentSlice = imp1.getCurrentSlice(); for (int n = 1; n <= slices; n++) { ip1 = stack1.getProcessor(n); ip3 = stack1.getProcessor(1); ip2 = stack2.getProcessor(n); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { v1 = ip1.getPixelValue(x, y); v2 = ip3.getPixelValue(x, y); // =B8/(EXP(-C$7*A8)) v1 = (v1 / Math.exp(-n * thalf)); ip2.putPixelValue(x, y, v1); } } IJ.showProgress((double) n / slices); IJ.showStatus(n + "/" + slices); } // stack2.show(); imp1.updateAndDraw(); }
void enlargeCanvas() { imp.unlock(); if (imp.getStackSize() == 1) Undo.setup(Undo.COMPOUND_FILTER, imp); IJ.run("Select All"); IJ.run("Rotate...", "angle=" + angle); Roi roi = imp.getRoi(); Rectangle r = roi.getBounds(); if (r.width < imp.getWidth()) r.width = imp.getWidth(); if (r.height < imp.getHeight()) r.height = imp.getHeight(); IJ.showStatus("Rotate: Enlarging..."); IJ.run( "Canvas Size...", "width=" + r.width + " height=" + r.height + " position=Center " + (fillWithBackground ? "" : "zero")); IJ.showStatus("Rotating..."); }
private void rotate(ImagePlus imp) { Roi roi = imp.getRoi(); if (IJ.macroRunning()) { String options = Macro.getOptions(); if (options != null && (options.indexOf("grid=") != -1 || options.indexOf("interpolat") != -1)) { IJ.run("Rotate... ", options); // run Image>Transform>Rotate return; } } (new RoiRotator()).run(""); }
void addToRoiManager(ImagePlus imp) { if (IJ.macroRunning() && Interpreter.isBatchModeRoiManager()) IJ.error("run(\"Add to Manager\") may not work in batch mode macros"); Frame frame = WindowManager.getFrame("ROI Manager"); if (frame == null) IJ.run("ROI Manager..."); if (imp == null) return; Roi roi = imp.getRoi(); if (roi == null) return; frame = WindowManager.getFrame("ROI Manager"); if (frame == null || !(frame instanceof RoiManager)) IJ.error("ROI Manager not found"); RoiManager rm = (RoiManager) frame; boolean altDown = IJ.altKeyDown(); IJ.setKeyUp(IJ.ALL_KEYS); if (altDown && !IJ.macroRunning()) IJ.setKeyDown(KeyEvent.VK_SHIFT); rm.runCommand("add"); IJ.setKeyUp(IJ.ALL_KEYS); }
void runMacro(String arg, ImagePlus imp) { boolean rotate = arg.equals("rotate"); Roi roi = imp.getRoi(); if (rotate && IJ.macroRunning()) { String options = Macro.getOptions(); if (options != null && (options.indexOf("grid=") != -1 || options.indexOf("interpolat") != -1)) { IJ.run("Rotate... ", options); // run Image>Transform>Rotate return; } } if (roi == null) { noRoi(rotate ? "Rotate" : "Enlarge"); return; } double dangle = Tools.parseDouble(angle); if (Double.isNaN(dangle)) { dangle = 15; angle = "" + dangle; } if (rotate && (roi instanceof ImageRoi)) { dangle = IJ.getNumber("Angle (degrees):", dangle); ((ImageRoi) roi).rotate(dangle); imp.draw(); angle = "" + dangle; return; } Undo.setup(Undo.ROI, imp); roi = (Roi) roi.clone(); if (rotate) { String value = IJ.runMacroFile("ij.jar:RotateSelection", angle); Roi roi2 = imp.getRoi(); transferProperties(roi, roi2); imp.setRoi(roi2); if (value != null) angle = value; } else if (arg.equals("enlarge")) (new RoiEnlarger()).run(""); }
void toRoiManager() { ImagePlus imp = IJ.getImage(); Overlay overlay = imp.getOverlay(); if (overlay == null) { IJ.error("Overlay required"); return; } RoiManager rm = RoiManager.getInstance(); if (rm == null) { if (Macro.getOptions() != null && Interpreter.isBatchMode()) rm = Interpreter.getBatchModeRoiManager(); if (rm == null) { Frame frame = WindowManager.getFrame("ROI Manager"); if (frame == null) IJ.run("ROI Manager..."); frame = WindowManager.getFrame("ROI Manager"); if (frame == null || !(frame instanceof RoiManager)) return; rm = (RoiManager) frame; } } rm.runCommand("reset"); for (int i = 0; i < overlay.size(); i++) rm.add(imp, overlay.get(i), i); rm.setEditMode(imp, true); if (rm.getCount() == overlay.size()) imp.setOverlay(null); }
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); }
void sample() { byte[] hsSource, ssSource, bsSource; // ImageProcessor ip2; // ip2 = imp.getProcessor(); Rectangle myroi = ip.getRoi(); int swidth = myroi.width; int sheight = myroi.height; int sy = myroi.y; int sx = myroi.x; if (swidth == width && sheight == height) { IJ.showMessage("Select a rectangular ROI"); IJ.beep(); return; } IJ.run("Select None"); int snumPixels = swidth * sheight; hsSource = new byte[snumPixels]; ssSource = new byte[snumPixels]; bsSource = new byte[snumPixels]; int[] pixs = new int[snumPixels]; int[] bin = new int[256]; int counter = 0, pi = 0, rangePassH = 0, rangeStopH = 0, rangePassL = 0, rangeStopL = 0, i, j; for (i = sy; i < sy + sheight; i++) { for (j = sx; j < sx + swidth; j++) { pixs[counter++] = ip.getPixel(j, i); } } // Get hsb or rgb from roi. ColorProcessor cp2 = new ColorProcessor(swidth, sheight, pixs); int iminhue = 256, imaxhue = -1, iminsat = 256, imaxsat = -1, iminbri = 256, imaxbri = -1; int iminred = 256, imaxred = -1, imingre = 256, imaxgre = -1, iminblu = 256, imaxblu = -1; if (isRGB) cp2.getRGB(hsSource, ssSource, bsSource); else cp2.getHSB(hsSource, ssSource, bsSource); for (i = 0; i < snumPixels; i++) { bin[hsSource[i] & 255] = 1; if ((hsSource[i] & 255) > imaxhue) imaxhue = (hsSource[i] & 255); if ((hsSource[i] & 255) < iminhue) iminhue = (hsSource[i] & 255); if ((ssSource[i] & 255) > imaxsat) imaxsat = (ssSource[i] & 255); if ((ssSource[i] & 255) < iminsat) iminsat = (ssSource[i] & 255); if ((bsSource[i] & 255) > imaxbri) imaxbri = (bsSource[i] & 255); if ((bsSource[i] & 255) < iminbri) iminbri = (bsSource[i] & 255); // IJ.showMessage("h:"+minhue+"H:"+maxhue+"s:"+minsat+"S:"+maxsat+"b:"+minbri+"B:"+maxbri); } if (!isRGB) { // get pass or stop filter whichever has a narrower range for (i = 0; i < 256; i++) { if (bin[i] > 0) { rangePassL = i; break; } } for (i = 255; i >= 0; i--) { if (bin[i] > 0) { rangePassH = i; break; } } for (i = 0; i < 256; i++) { if (bin[i] == 0) { rangeStopL = i; break; } } for (i = 255; i >= 0; i--) { if (bin[i] == 0) { rangeStopH = i; break; } } if ((rangePassH - rangePassL) < (rangeStopH - rangeStopL)) { bandPassH.setState(true); bandStopH.setState(false); iminhue = rangePassL; imaxhue = rangePassH; } else { bandPassH.setState(false); bandStopH.setState(true); iminhue = rangeStopL; imaxhue = rangeStopH; } } else { bandPassH.setState(true); bandStopH.setState(false); } adjustMinHue(iminhue); minSlider.setValue(iminhue); adjustMaxHue(imaxhue); maxSlider.setValue(imaxhue); adjustMinSat(iminsat); minSlider2.setValue(iminsat); adjustMaxSat(imaxsat); maxSlider2.setValue(imaxsat); adjustMinBri(iminbri); minSlider3.setValue(iminbri); adjustMaxBri(imaxbri); maxSlider3.setValue(imaxbri); originalB.setEnabled(true); // IJ.showStatus("done"); }
public void build_bricks() { ImagePlus imp; ImagePlus orgimp; ImageStack stack; FileInfo finfo; if (lvImgTitle.isEmpty()) return; orgimp = WindowManager.getImage(lvImgTitle.get(0)); imp = orgimp; finfo = imp.getFileInfo(); if (finfo == null) return; int[] dims = imp.getDimensions(); int imageW = dims[0]; int imageH = dims[1]; int nCh = dims[2]; int imageD = dims[3]; int nFrame = dims[4]; int bdepth = imp.getBitDepth(); double xspc = finfo.pixelWidth; double yspc = finfo.pixelHeight; double zspc = finfo.pixelDepth; double z_aspect = Math.max(xspc, yspc) / zspc; int orgW = imageW; int orgH = imageH; int orgD = imageD; double orgxspc = xspc; double orgyspc = yspc; double orgzspc = zspc; lv = lvImgTitle.size(); if (filetype == "JPEG") { for (int l = 0; l < lv; l++) { if (WindowManager.getImage(lvImgTitle.get(l)).getBitDepth() != 8) { IJ.error("A SOURCE IMAGE MUST BE 8BIT GLAYSCALE"); return; } } } // calculate levels /* int baseXY = 256; int baseZ = 256; if (z_aspect < 0.5) baseZ = 128; if (z_aspect > 2.0) baseXY = 128; if (z_aspect >= 0.5 && z_aspect < 1.0) baseZ = (int)(baseZ*z_aspect); if (z_aspect > 1.0 && z_aspect <= 2.0) baseXY = (int)(baseXY/z_aspect); IJ.log("Z_aspect: " + z_aspect); IJ.log("BaseXY: " + baseXY); IJ.log("BaseZ: " + baseZ); */ int baseXY = 256; int baseZ = 128; int dbXY = Math.max(orgW, orgH) / baseXY; if (Math.max(orgW, orgH) % baseXY > 0) dbXY *= 2; int dbZ = orgD / baseZ; if (orgD % baseZ > 0) dbZ *= 2; lv = Math.max(log2(dbXY), log2(dbZ)) + 1; int ww = orgW; int hh = orgH; int dd = orgD; for (int l = 0; l < lv; l++) { int bwnum = ww / baseXY; if (ww % baseXY > 0) bwnum++; int bhnum = hh / baseXY; if (hh % baseXY > 0) bhnum++; int bdnum = dd / baseZ; if (dd % baseZ > 0) bdnum++; if (bwnum % 2 == 0) bwnum++; if (bhnum % 2 == 0) bhnum++; if (bdnum % 2 == 0) bdnum++; int bw = (bwnum <= 1) ? ww : ww / bwnum + 1 + (ww % bwnum > 0 ? 1 : 0); int bh = (bhnum <= 1) ? hh : hh / bhnum + 1 + (hh % bhnum > 0 ? 1 : 0); int bd = (bdnum <= 1) ? dd : dd / bdnum + 1 + (dd % bdnum > 0 ? 1 : 0); bwlist.add(bw); bhlist.add(bh); bdlist.add(bd); IJ.log("LEVEL: " + l); IJ.log(" width: " + ww); IJ.log(" hight: " + hh); IJ.log(" depth: " + dd); IJ.log(" bw: " + bw); IJ.log(" bh: " + bh); IJ.log(" bd: " + bd); int xyl2 = Math.max(ww, hh) / baseXY; if (Math.max(ww, hh) % baseXY > 0) xyl2 *= 2; if (lv - 1 - log2(xyl2) <= l) { ww /= 2; hh /= 2; } IJ.log(" xyl2: " + (lv - 1 - log2(xyl2))); int zl2 = dd / baseZ; if (dd % baseZ > 0) zl2 *= 2; if (lv - 1 - log2(zl2) <= l) dd /= 2; IJ.log(" zl2: " + (lv - 1 - log2(zl2))); if (l < lv - 1) { lvImgTitle.add(lvImgTitle.get(0) + "_level" + (l + 1)); IJ.selectWindow(lvImgTitle.get(0)); IJ.run( "Scale...", "x=- y=- z=- width=" + ww + " height=" + hh + " depth=" + dd + " interpolation=Bicubic average process create title=" + lvImgTitle.get(l + 1)); } } for (int l = 0; l < lv; l++) { IJ.log(lvImgTitle.get(l)); } Document doc = newXMLDocument(); Element root = doc.createElement("BRK"); root.setAttribute("version", "1.0"); root.setAttribute("nLevel", String.valueOf(lv)); root.setAttribute("nChannel", String.valueOf(nCh)); root.setAttribute("nFrame", String.valueOf(nFrame)); doc.appendChild(root); for (int l = 0; l < lv; l++) { IJ.showProgress(0.0); int[] dims2 = imp.getDimensions(); IJ.log( "W: " + String.valueOf(dims2[0]) + " H: " + String.valueOf(dims2[1]) + " C: " + String.valueOf(dims2[2]) + " D: " + String.valueOf(dims2[3]) + " T: " + String.valueOf(dims2[4]) + " b: " + String.valueOf(bdepth)); bw = bwlist.get(l).intValue(); bh = bhlist.get(l).intValue(); bd = bdlist.get(l).intValue(); boolean force_pow2 = false; /* if(IsPowerOf2(bw) && IsPowerOf2(bh) && IsPowerOf2(bd)) force_pow2 = true; if(force_pow2){ //force pow2 if(Pow2(bw) > bw) bw = Pow2(bw)/2; if(Pow2(bh) > bh) bh = Pow2(bh)/2; if(Pow2(bd) > bd) bd = Pow2(bd)/2; } if(bw > imageW) bw = (Pow2(imageW) == imageW) ? imageW : Pow2(imageW)/2; if(bh > imageH) bh = (Pow2(imageH) == imageH) ? imageH : Pow2(imageH)/2; if(bd > imageD) bd = (Pow2(imageD) == imageD) ? imageD : Pow2(imageD)/2; */ if (bw > imageW) bw = imageW; if (bh > imageH) bh = imageH; if (bd > imageD) bd = imageD; if (bw <= 1 || bh <= 1 || bd <= 1) break; if (filetype == "JPEG" && (bw < 8 || bh < 8)) break; Element lvnode = doc.createElement("Level"); lvnode.setAttribute("lv", String.valueOf(l)); lvnode.setAttribute("imageW", String.valueOf(imageW)); lvnode.setAttribute("imageH", String.valueOf(imageH)); lvnode.setAttribute("imageD", String.valueOf(imageD)); lvnode.setAttribute("xspc", String.valueOf(xspc)); lvnode.setAttribute("yspc", String.valueOf(yspc)); lvnode.setAttribute("zspc", String.valueOf(zspc)); lvnode.setAttribute("bitDepth", String.valueOf(bdepth)); root.appendChild(lvnode); Element brksnode = doc.createElement("Bricks"); brksnode.setAttribute("brick_baseW", String.valueOf(bw)); brksnode.setAttribute("brick_baseH", String.valueOf(bh)); brksnode.setAttribute("brick_baseD", String.valueOf(bd)); lvnode.appendChild(brksnode); ArrayList<Brick> bricks = new ArrayList<Brick>(); int mw, mh, md, mw2, mh2, md2; double tx0, ty0, tz0, tx1, ty1, tz1; double bx0, by0, bz0, bx1, by1, bz1; for (int k = 0; k < imageD; k += bd) { if (k > 0) k--; for (int j = 0; j < imageH; j += bh) { if (j > 0) j--; for (int i = 0; i < imageW; i += bw) { if (i > 0) i--; mw = Math.min(bw, imageW - i); mh = Math.min(bh, imageH - j); md = Math.min(bd, imageD - k); if (force_pow2) { mw2 = Pow2(mw); mh2 = Pow2(mh); md2 = Pow2(md); } else { mw2 = mw; mh2 = mh; md2 = md; } if (filetype == "JPEG") { if (mw2 < 8) mw2 = 8; if (mh2 < 8) mh2 = 8; } tx0 = i == 0 ? 0.0d : ((mw2 - mw + 0.5d) / mw2); ty0 = j == 0 ? 0.0d : ((mh2 - mh + 0.5d) / mh2); tz0 = k == 0 ? 0.0d : ((md2 - md + 0.5d) / md2); tx1 = 1.0d - 0.5d / mw2; if (mw < bw) tx1 = 1.0d; if (imageW - i == bw) tx1 = 1.0d; ty1 = 1.0d - 0.5d / mh2; if (mh < bh) ty1 = 1.0d; if (imageH - j == bh) ty1 = 1.0d; tz1 = 1.0d - 0.5d / md2; if (md < bd) tz1 = 1.0d; if (imageD - k == bd) tz1 = 1.0d; bx0 = i == 0 ? 0.0d : (i + 0.5d) / (double) imageW; by0 = j == 0 ? 0.0d : (j + 0.5d) / (double) imageH; bz0 = k == 0 ? 0.0d : (k + 0.5d) / (double) imageD; bx1 = Math.min((i + bw - 0.5d) / (double) imageW, 1.0d); if (imageW - i == bw) bx1 = 1.0d; by1 = Math.min((j + bh - 0.5d) / (double) imageH, 1.0d); if (imageH - j == bh) by1 = 1.0d; bz1 = Math.min((k + bd - 0.5d) / (double) imageD, 1.0d); if (imageD - k == bd) bz1 = 1.0d; int x, y, z; x = i - (mw2 - mw); y = j - (mh2 - mh); z = k - (md2 - md); bricks.add( new Brick( x, y, z, mw2, mh2, md2, 0, 0, tx0, ty0, tz0, tx1, ty1, tz1, bx0, by0, bz0, bx1, by1, bz1)); } } } Element fsnode = doc.createElement("Files"); lvnode.appendChild(fsnode); stack = imp.getStack(); int totalbricknum = nFrame * nCh * bricks.size(); int curbricknum = 0; for (int f = 0; f < nFrame; f++) { for (int ch = 0; ch < nCh; ch++) { int sizelimit = bdsizelimit * 1024 * 1024; int bytecount = 0; int filecount = 0; int pd_bufsize = Math.max(sizelimit, bw * bh * bd * bdepth / 8); byte[] packed_data = new byte[pd_bufsize]; String base_dataname = basename + "_Lv" + String.valueOf(l) + "_Ch" + String.valueOf(ch) + "_Fr" + String.valueOf(f); String current_dataname = base_dataname + "_data" + filecount; Brick b_first = bricks.get(0); if (b_first.z_ != 0) IJ.log("warning"); int st_z = b_first.z_; int ed_z = b_first.z_ + b_first.d_; LinkedList<ImageProcessor> iplist = new LinkedList<ImageProcessor>(); for (int s = st_z; s < ed_z; s++) iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1))); // ImagePlus test; // ImageStack tsst; // test = NewImage.createByteImage("test", imageW, imageH, imageD, // NewImage.FILL_BLACK); // tsst = test.getStack(); for (int i = 0; i < bricks.size(); i++) { Brick b = bricks.get(i); if (ed_z > b.z_ || st_z < b.z_ + b.d_) { if (b.z_ > st_z) { for (int s = 0; s < b.z_ - st_z; s++) iplist.pollFirst(); st_z = b.z_; } else if (b.z_ < st_z) { IJ.log("warning"); for (int s = st_z - 1; s > b.z_; s--) iplist.addFirst(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1))); st_z = b.z_; } if (b.z_ + b.d_ > ed_z) { for (int s = ed_z; s < b.z_ + b.d_; s++) iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1))); ed_z = b.z_ + b.d_; } else if (b.z_ + b.d_ < ed_z) { IJ.log("warning"); for (int s = 0; s < ed_z - (b.z_ + b.d_); s++) iplist.pollLast(); ed_z = b.z_ + b.d_; } } else { IJ.log("warning"); iplist.clear(); st_z = b.z_; ed_z = b.z_ + b.d_; for (int s = st_z; s < ed_z; s++) iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1))); } if (iplist.size() != b.d_) { IJ.log("Stack Error"); return; } // int zz = st_z; int bsize = 0; byte[] bdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8]; Iterator<ImageProcessor> ipite = iplist.iterator(); while (ipite.hasNext()) { // ImageProcessor tsip = tsst.getProcessor(zz+1); ImageProcessor ip = ipite.next(); ip.setRoi(b.x_, b.y_, b.w_, b.h_); if (bdepth == 8) { byte[] data = (byte[]) ip.crop().getPixels(); System.arraycopy(data, 0, bdata, bsize, data.length); bsize += data.length; } else if (bdepth == 16) { ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8); buffer.order(ByteOrder.LITTLE_ENDIAN); short[] data = (short[]) ip.crop().getPixels(); for (short e : data) buffer.putShort(e); System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length); bsize += buffer.array().length; } else if (bdepth == 32) { ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8); buffer.order(ByteOrder.LITTLE_ENDIAN); float[] data = (float[]) ip.crop().getPixels(); for (float e : data) buffer.putFloat(e); System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length); bsize += buffer.array().length; } } String filename = basename + "_Lv" + String.valueOf(l) + "_Ch" + String.valueOf(ch) + "_Fr" + String.valueOf(f) + "_ID" + String.valueOf(i); int offset = bytecount; int datasize = bdata.length; if (filetype == "RAW") { int dummy = -1; // do nothing } if (filetype == "JPEG" && bdepth == 8) { try { DataBufferByte db = new DataBufferByte(bdata, datasize); Raster raster = Raster.createPackedRaster(db, b.w_, b.h_ * b.d_, 8, null); BufferedImage img = new BufferedImage(b.w_, b.h_ * b.d_, BufferedImage.TYPE_BYTE_GRAY); img.setData(raster); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageOutputStream ios = ImageIO.createImageOutputStream(baos); String format = "jpg"; Iterator<javax.imageio.ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg"); javax.imageio.ImageWriter writer = iter.next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality((float) jpeg_quality * 0.01f); writer.setOutput(ios); writer.write(null, new IIOImage(img, null, null), iwp); // ImageIO.write(img, format, baos); bdata = baos.toByteArray(); datasize = bdata.length; } catch (IOException e) { e.printStackTrace(); return; } } if (filetype == "ZLIB") { byte[] tmpdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8]; Deflater compresser = new Deflater(); compresser.setInput(bdata); compresser.setLevel(Deflater.DEFAULT_COMPRESSION); compresser.setStrategy(Deflater.DEFAULT_STRATEGY); compresser.finish(); datasize = compresser.deflate(tmpdata); bdata = tmpdata; compresser.end(); } if (bytecount + datasize > sizelimit && bytecount > 0) { BufferedOutputStream fis = null; try { File file = new File(directory + current_dataname); fis = new BufferedOutputStream(new FileOutputStream(file)); fis.write(packed_data, 0, bytecount); } catch (IOException e) { e.printStackTrace(); return; } finally { try { if (fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); return; } } filecount++; current_dataname = base_dataname + "_data" + filecount; bytecount = 0; offset = 0; System.arraycopy(bdata, 0, packed_data, bytecount, datasize); bytecount += datasize; } else { System.arraycopy(bdata, 0, packed_data, bytecount, datasize); bytecount += datasize; } Element filenode = doc.createElement("File"); filenode.setAttribute("filename", current_dataname); filenode.setAttribute("channel", String.valueOf(ch)); filenode.setAttribute("frame", String.valueOf(f)); filenode.setAttribute("brickID", String.valueOf(i)); filenode.setAttribute("offset", String.valueOf(offset)); filenode.setAttribute("datasize", String.valueOf(datasize)); filenode.setAttribute("filetype", String.valueOf(filetype)); fsnode.appendChild(filenode); curbricknum++; IJ.showProgress((double) (curbricknum) / (double) (totalbricknum)); } if (bytecount > 0) { BufferedOutputStream fis = null; try { File file = new File(directory + current_dataname); fis = new BufferedOutputStream(new FileOutputStream(file)); fis.write(packed_data, 0, bytecount); } catch (IOException e) { e.printStackTrace(); return; } finally { try { if (fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); return; } } } } } for (int i = 0; i < bricks.size(); i++) { Brick b = bricks.get(i); Element bricknode = doc.createElement("Brick"); bricknode.setAttribute("id", String.valueOf(i)); bricknode.setAttribute("st_x", String.valueOf(b.x_)); bricknode.setAttribute("st_y", String.valueOf(b.y_)); bricknode.setAttribute("st_z", String.valueOf(b.z_)); bricknode.setAttribute("width", String.valueOf(b.w_)); bricknode.setAttribute("height", String.valueOf(b.h_)); bricknode.setAttribute("depth", String.valueOf(b.d_)); brksnode.appendChild(bricknode); Element tboxnode = doc.createElement("tbox"); tboxnode.setAttribute("x0", String.valueOf(b.tx0_)); tboxnode.setAttribute("y0", String.valueOf(b.ty0_)); tboxnode.setAttribute("z0", String.valueOf(b.tz0_)); tboxnode.setAttribute("x1", String.valueOf(b.tx1_)); tboxnode.setAttribute("y1", String.valueOf(b.ty1_)); tboxnode.setAttribute("z1", String.valueOf(b.tz1_)); bricknode.appendChild(tboxnode); Element bboxnode = doc.createElement("bbox"); bboxnode.setAttribute("x0", String.valueOf(b.bx0_)); bboxnode.setAttribute("y0", String.valueOf(b.by0_)); bboxnode.setAttribute("z0", String.valueOf(b.bz0_)); bboxnode.setAttribute("x1", String.valueOf(b.bx1_)); bboxnode.setAttribute("y1", String.valueOf(b.by1_)); bboxnode.setAttribute("z1", String.valueOf(b.bz1_)); bricknode.appendChild(bboxnode); } if (l < lv - 1) { imp = WindowManager.getImage(lvImgTitle.get(l + 1)); int[] newdims = imp.getDimensions(); imageW = newdims[0]; imageH = newdims[1]; imageD = newdims[3]; xspc = orgxspc * ((double) orgW / (double) imageW); yspc = orgyspc * ((double) orgH / (double) imageH); zspc = orgzspc * ((double) orgD / (double) imageD); bdepth = imp.getBitDepth(); } } File newXMLfile = new File(directory + basename + ".vvd"); writeXML(newXMLfile, doc); for (int l = 1; l < lv; l++) { imp = WindowManager.getImage(lvImgTitle.get(l)); imp.changes = false; imp.close(); } }
public void run(String arg) { ImageCheck ic = new ImageCheck(); if (!ImageCheck.checkEnvironment()) return; ImagePlus imp = IJ.getImage(); if (!ic.isBinary(imp)) { IJ.error("8-bit binary (black and white only) image required."); return; } if (!ic.isVoxelIsotropic(imp, 1E-3)) { if (IJ.showMessageWithCancel( "Anisotropic voxels", "This image contains anisotropic voxels, which will\n" + "result in incorrect thickness calculation.\n\n" + "Consider rescaling your data so that voxels are isotropic\n" + "(Image > Scale...).\n\n" + "Continue anyway?")) { } else return; } GenericDialog gd = new GenericDialog("Options"); gd.addCheckbox("Thickness", true); gd.addCheckbox("Spacing", false); gd.addCheckbox("Graphic Result", true); gd.addCheckbox("Use_ROI_Manager", false); gd.addCheckbox("Mask thickness map", true); gd.addHelp("http://bonej.org/thickness"); gd.showDialog(); if (gd.wasCanceled()) { return; } boolean doThickness = gd.getNextBoolean(); boolean doSpacing = gd.getNextBoolean(); boolean doGraphic = gd.getNextBoolean(); boolean doRoi = gd.getNextBoolean(); boolean doMask = gd.getNextBoolean(); long startTime = System.currentTimeMillis(); String title = stripExtension(imp.getTitle()); RoiManager roiMan = RoiManager.getInstance(); // calculate trabecular thickness (Tb.Th) if (doThickness) { boolean inverse = false; ImagePlus impLTC = new ImagePlus(); if (doRoi && roiMan != null) { ImageStack stack = RoiMan.cropStack(roiMan, imp.getStack(), true, 0, 1); ImagePlus crop = new ImagePlus(imp.getTitle(), stack); crop.setCalibration(imp.getCalibration()); impLTC = getLocalThickness(crop, inverse, doMask); } else impLTC = getLocalThickness(imp, inverse, doMask); impLTC.setTitle(title + "_Tb.Th"); impLTC.setCalibration(imp.getCalibration()); double[] stats = StackStats.meanStdDev(impLTC); insertResults(imp, stats, inverse); if (doGraphic && !Interpreter.isBatchMode()) { impLTC.show(); impLTC.setSlice(1); impLTC.getProcessor().setMinAndMax(0, stats[2]); IJ.run("Fire"); } } if (doSpacing) { boolean inverse = true; ImagePlus impLTCi = new ImagePlus(); if (doRoi && roiMan != null) { ImageStack stack = RoiMan.cropStack(roiMan, imp.getStack(), true, 255, 1); ImagePlus crop = new ImagePlus(imp.getTitle(), stack); crop.setCalibration(imp.getCalibration()); impLTCi = getLocalThickness(crop, inverse, doMask); } else impLTCi = getLocalThickness(imp, inverse, doMask); // check marrow cavity size (i.e. trabcular separation, Tb.Sp) impLTCi.setTitle(title + "_Tb.Sp"); impLTCi.setCalibration(imp.getCalibration()); double[] stats = StackStats.meanStdDev(impLTCi); insertResults(imp, stats, inverse); if (doGraphic && !Interpreter.isBatchMode()) { impLTCi.show(); impLTCi.setSlice(1); impLTCi.getProcessor().setMinAndMax(0, stats[2]); IJ.run("Fire"); } } IJ.showProgress(1.0); IJ.showStatus("Done"); double duration = ((double) System.currentTimeMillis() - (double) startTime) / (double) 1000; IJ.log("Duration = " + IJ.d2s(duration, 3) + " s"); UsageReporter.reportEvent(this).send(); return; }
public void run(String arg) { int[] wList = WindowManager.getIDList(); if (wList==null) { IJ.error("No images are open."); return; } double kernel=3; double kernelsum = 0; double kernelvarsum =0; double kernalvar = 0; double sigmawidth = 2; int kernelindex, minpixnumber; String[] kernelsize = { "3�,"5�, "7�, "9�}; GenericDialog gd = new GenericDialog("Sigma Filter"); gd.addChoice("Kernel size", kernelsize, kernelsize[0]); gd.addNumericField("Sigma width",sigmawidth , 2); gd.addNumericField("Minimum number of pixels", 1, 0); gd.addCheckbox("Keep source:",true); gd.addCheckbox("Do all stack:",true); gd.addCheckbox("Modified Lee's FIlter:",true); gd.showDialog(); if (gd.wasCanceled()) return ; kernelindex = gd.getNextChoiceIndex(); sigmawidth = gd.getNextNumber(); minpixnumber = ((int)gd.getNextNumber()); boolean keep = gd.getNextBoolean(); boolean doallstack = gd.getNextBoolean(); boolean modified = gd.getNextBoolean(); if (kernelindex==0) kernel = 3; if (kernelindex==1) kernel = 5; if (kernelindex==2) kernel = 7; if (kernelindex==3) kernel = 9; long start = System.currentTimeMillis(); if (minpixnumber> (kernel*kernel)){ IJ.showMessage("Sigma filter", "There must be more pixels in the kernel than+\n" + "the minimum number to be included"); return; } double v, midintensity; int x, y, ix, iy; double sum = 0; double backupsum =0; int count = 0; int n = 0; if (keep) {IJ.run("Select All"); IJ.run("Duplicate...", "title='Sigma filtered' duplicate");} int radius = (int)(kernel-1)/2; ImagePlus imp = WindowManager.getCurrentImage(); ImageStack stack1 = imp.getStack(); int width = imp.getWidth(); int height = imp.getHeight(); int nslices = stack1.getSize(); int cslice = imp.getCurrentSlice(); double status = width*height*nslices; ImageProcessor ip = imp.getProcessor(); int sstart = 1; if (!doallstack) {sstart = cslice; nslices=sstart;status = status/nslices;}; for (int i=sstart; i<=nslices; i++) { imp.setSlice(i); for (x=radius;x<width+radius;x++) { for (y=radius;y<height+radius;y++) { midintensity = ip.getPixelValue(x,y); count = 0; sum = 0; kernelsum =0; kernalvar =0; kernelvarsum =0; backupsum = 0; //calculate mean of kernel value for (ix=0;ix<kernel;ix++) { for (iy=0;iy<kernel;iy++) { v = ip.getPixelValue(x+ix-radius,y+iy-radius); kernelsum = kernelsum+v; } } double sigmacalcmean = (kernelsum/(kernel*kernel)); //calculate variance of kernel for (ix=0;ix<kernel;ix++) { for (iy=0;iy<kernel;iy++) { v = ip.getPixelValue(x+ix-radius,y+iy-radius); kernalvar = (v-sigmacalcmean)*(v-sigmacalcmean); kernelvarsum = kernelvarsum + kernalvar; } } //double variance = kernelvarsum/kernel; double sigmacalcvar = kernelvarsum/((kernel*kernel)-1); //calcuate sigma range = sqrt(variance/(mean^2)) � sigmawidth double sigmarange = sigmawidth*(Math.sqrt((sigmacalcvar) /(sigmacalcmean*sigmacalcmean))); //calulate sigma top value and bottom value double sigmatop = midintensity*(1+sigmarange); double sigmabottom = midintensity*(1-sigmarange); //calculate mean of values that differ are in sigma range. for (ix=0;ix<kernel;ix++) { for (iy=0;iy<kernel;iy++) { v = ip.getPixelValue(x+ix-radius,y+iy-radius); if ((v>=sigmabottom)&&(v<=sigmatop)){ sum = sum+v; count = count+1; } backupsum = v+ backupsum; } } //if there are too few pixels in the kernal that are within sigma range, the //mean of the entire kernal is taken. My modification of Lee's filter is to exclude the central value //from the calculation of the mean as I assume it to be spuriously high or low if (!(count>(minpixnumber))) {sum = (backupsum-midintensity); count = (int)((kernel*kernel)-1); if (!modified) {sum = (backupsum); count = (int)(kernel*kernel);} } double val = (sum/count); ip.putPixelValue(x,y, val); n = n+1; double percentage = (((double)n/status)*100); IJ.showStatus(IJ.d2s(percentage,0) +"% done"); } // IJ.showProgress(i, status); }} imp.updateAndDraw(); IJ.showStatus(IJ.d2s((System.currentTimeMillis()-start)/1000.0, 2)+" seconds"); }
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(); }
/** 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 boolean install(String path) { boolean isURL = path.contains("://"); String lcPath = path.toLowerCase(); if (isURL) path = Opener.updateUrl(path); boolean isTool = lcPath.endsWith("tool.ijm") || lcPath.endsWith("tool.txt") || lcPath.endsWith("tool.class") || lcPath.endsWith("tool.jar"); boolean isMacro = lcPath.endsWith(".txt") || lcPath.endsWith(".ijm"); byte[] data = null; String name = path; if (isURL) { int index = path.lastIndexOf("/"); if (index != -1 && index <= path.length() - 1) name = path.substring(index + 1); data = download(path, name); } else { File f = new File(path); name = f.getName(); data = download(f); } if (data == null) return false; if (name.endsWith(".txt") && !name.contains("_")) name = name.substring(0, name.length() - 4) + ".ijm"; if (name.endsWith(".zip")) { if (!name.contains("_")) { IJ.error("Plugin Installer", "No underscore in file name:\n \n " + name); return false; } name = name.substring(0, name.length() - 4) + ".jar"; } String dir = null; boolean isLibrary = name.endsWith(".jar") && !name.contains("_"); if (isLibrary) { dir = Menus.getPlugInsPath() + "jars"; File f = new File(dir); if (!f.exists()) { boolean ok = f.mkdir(); if (!ok) dir = Menus.getPlugInsPath(); } } if (isTool) { dir = Menus.getPlugInsPath() + "Tools" + File.separator; File f = new File(dir); if (!f.exists()) { boolean ok = f.mkdir(); if (!ok) dir = null; } if (dir != null && isMacro) { String name2 = getToolName(data); if (name2 != null) name = name2; } } if (dir == null) { SaveDialog sd = new SaveDialog("Save Plugin, Macro or Script...", Menus.getPlugInsPath(), name, null); String name2 = sd.getFileName(); if (name2 == null) return false; dir = sd.getDirectory(); } // IJ.log(dir+" "+Menus.getPlugInsPath()); if (!savePlugin(new File(dir, name), data)) return false; if (name.endsWith(".java")) IJ.runPlugIn("ij.plugin.Compiler", dir + name); Menus.updateImageJMenus(); if (isTool) { if (isMacro) IJ.runPlugIn("ij.plugin.Macro_Runner", "Tools/" + name); else if (name.endsWith(".class")) { name = name.replaceAll("_", " "); name = name.substring(0, name.length() - 6); IJ.run(name); } } return true; }
public void run(String arg) { String lutDir = Prefs.getHomeDir() + File.separator + "lut" + File.separator; IJ.run("LUT... ", "open=" + "'" + lutDir + "Rainbow Smooth.lut" + "'"); }
private void makeBand(ImagePlus imp) { Roi roi = imp.getRoi(); if (roi == null) { noRoi("Make Band"); return; } if (!roi.isArea()) { IJ.error("Make Band", "Area selection required"); return; } Calibration cal = imp.getCalibration(); double pixels = bandSize; double size = pixels * cal.pixelWidth; int decimalPlaces = 0; if ((int) size != size) decimalPlaces = 2; GenericDialog gd = new GenericDialog("Make Band"); gd.addNumericField("Band Size:", size, decimalPlaces, 4, cal.getUnits()); gd.showDialog(); if (gd.wasCanceled()) return; size = gd.getNextNumber(); if (Double.isNaN(size)) { IJ.error("Make Band", "invalid number"); return; } int n = (int) Math.round(size / cal.pixelWidth); if (n > 255) { IJ.error("Make Band", "Cannot make bands wider that 255 pixels"); return; } int width = imp.getWidth(); int height = imp.getHeight(); Rectangle r = roi.getBounds(); ImageProcessor ip = roi.getMask(); if (ip == null) { ip = new ByteProcessor(r.width, r.height); ip.invert(); } ImageProcessor mask = new ByteProcessor(width, height); mask.insert(ip, r.x, r.y); ImagePlus edm = new ImagePlus("mask", mask); boolean saveBlackBackground = Prefs.blackBackground; Prefs.blackBackground = false; IJ.run(edm, "Distance Map", ""); Prefs.blackBackground = saveBlackBackground; ip = edm.getProcessor(); ip.setThreshold(0, n, ImageProcessor.NO_LUT_UPDATE); int xx = -1, yy = -1; for (int x = r.x; x < r.x + r.width; x++) { for (int y = r.y; y < r.y + r.height; y++) { if (ip.getPixel(x, y) < n) { xx = x; yy = y; break; } } if (xx >= 0 || yy >= 0) break; } int count = IJ.doWand(edm, xx, yy, 0, null); if (count <= 0) { IJ.error("Make Band", "Unable to make band"); return; } ShapeRoi roi2 = new ShapeRoi(edm.getRoi()); if (!(roi instanceof ShapeRoi)) roi = new ShapeRoi(roi); ShapeRoi roi1 = (ShapeRoi) roi; roi2 = roi2.not(roi1); imp.setRoi(roi2); bandSize = n; }
public void run(String arg) { imp = IJ.getImage(); int stackSize = imp.getStackSize(); if (imp == null) { IJ.noImage(); return; } // Make sure input image is a stack. if (stackSize == 1) { IJ.error("Z Project", "Stack required"); return; } // Check for inverting LUT. if (imp.getProcessor().isInvertedLut()) { if (!IJ.showMessageWithCancel("ZProjection", lutMessage)) return; } // Set default bounds. int channels = imp.getNChannels(); int frames = imp.getNFrames(); int slices = imp.getNSlices(); isHyperstack = imp.isHyperStack() || (ij.macro.Interpreter.isBatchMode() && ((frames > 1 && frames < stackSize) || (slices > 1 && slices < stackSize))); boolean simpleComposite = channels == stackSize; if (simpleComposite) isHyperstack = false; startSlice = 1; if (isHyperstack) { int nSlices = imp.getNSlices(); if (nSlices > 1) stopSlice = nSlices; else stopSlice = imp.getNFrames(); } else stopSlice = stackSize; // Build control dialog GenericDialog gd = buildControlDialog(startSlice, stopSlice); gd.showDialog(); if (gd.wasCanceled()) return; if (!imp.lock()) return; // exit if in use long tstart = System.currentTimeMillis(); setStartSlice((int) gd.getNextNumber()); setStopSlice((int) gd.getNextNumber()); method = gd.getNextChoiceIndex(); Prefs.set(METHOD_KEY, method); if (isHyperstack) { allTimeFrames = imp.getNFrames() > 1 && imp.getNSlices() > 1 ? gd.getNextBoolean() : false; doHyperStackProjection(allTimeFrames); } else if (imp.getType() == ImagePlus.COLOR_RGB) doRGBProjection(true); else doProjection(true); if (arg.equals("") && projImage != null) { long tstop = System.currentTimeMillis(); projImage.setCalibration(imp.getCalibration()); if (simpleComposite) IJ.run(projImage, "Grays", ""); projImage.show("ZProjector: " + IJ.d2s((tstop - tstart) / 1000.0, 2) + " seconds"); } imp.unlock(); IJ.register(ZProjector.class); return; }