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); }
void loadTransformation(String filename, ResultsTable res) { try { String line; FileReader fr = new FileReader(filename); BufferedReader br = new BufferedReader(fr); if (!br.readLine().equals(" Z-Step Raw Width minus Heigh Calibration Width minus Height")) { IJ.error("File does not seam to be an Astigmatism calibration file"); return; } // java.lang.String [] elements = new java.lang.String [3]; java.lang.String[] elements; int counter = 1; res.reset(); while ((line = br.readLine()) != null) { IJ.showStatus("Loading element " + counter + "... sit back and relax."); counter++; line.trim(); elements = line.split("\t"); res.incrementCounter(); res.addValue("Z-Step", Double.parseDouble(elements[1])); res.addValue("Raw Width minus Heigh", Double.parseDouble(elements[2])); res.addValue("Calibration Width minus Height", Double.parseDouble(elements[3])); } fr.close(); } catch (FileNotFoundException e) { IJ.error("File not found exception" + e); return; } catch (IOException e) { IJ.error("IOException exception" + e); return; } catch (NumberFormatException e) { IJ.error("Number format exception" + e); return; } }
void fitSpline() { Roi roi = imp.getRoi(); if (roi == null) { IJ.error("Spline", "Selection required"); return; } int type = roi.getType(); boolean segmentedSelection = type == Roi.POLYGON || type == Roi.POLYLINE; if (!(segmentedSelection || type == Roi.FREEROI || type == Roi.TRACED_ROI || type == Roi.FREELINE)) { IJ.error("Spline", "Polygon or polyline selection required"); return; } if (roi instanceof EllipseRoi) return; PolygonRoi p = (PolygonRoi) roi; if (!segmentedSelection) p = trimPolygon(p, p.getUncalibratedLength()); String options = Macro.getOptions(); if (options != null && options.indexOf("straighten") != -1) p.fitSplineForStraightening(); else if (options != null && options.indexOf("remove") != -1) p.removeSplineFit(); else p.fitSpline(); imp.draw(); LineWidthAdjuster.update(); }
void lineToArea(ImagePlus imp) { Roi roi = imp.getRoi(); if (roi == null || !roi.isLine()) { IJ.error("Line to Area", "Line selection required"); return; } if (roi.getType() == Roi.LINE && roi.getStrokeWidth() == 1) { IJ.error("Line to Area", "Straight line width must be > 1"); return; } ImageProcessor ip2 = new ByteProcessor(imp.getWidth(), imp.getHeight()); ip2.setColor(255); if (roi.getType() == Roi.LINE) ip2.fillPolygon(roi.getPolygon()); else { roi.drawPixels(ip2); // BufferedImage bi = new BufferedImage(imp.getWidth(), imp.getHeight(), // BufferedImage.TYPE_BYTE_GRAY); // Graphics g = bi.getGraphics(); // Roi roi2 = (Roi)roi.clone(); // roi2.setStrokeColor(Color.white); // roi2.drawOverlay(g); // ip2 = new ByteProcessor(bi); } // new ImagePlus("ip2", ip2.duplicate()).show(); ip2.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE); ThresholdToSelection tts = new ThresholdToSelection(); Roi roi2 = tts.convert(ip2); imp.setRoi(roi2); Roi.previousRoi = (Roi) roi.clone(); }
/** * Attempts to open the specified inputStream as a TIFF, returning an ImagePlus object if * successful. */ public ImagePlus openTiff(InputStream in, String name) { FileInfo[] info = null; try { TiffDecoder td = new TiffDecoder(in, name); if (IJ.debugMode) td.enableDebugging(); info = td.getTiffInfo(); } catch (FileNotFoundException e) { IJ.error("Open TIFF", "File not found: " + e.getMessage()); return null; } catch (Exception e) { IJ.error("Open TIFF", "" + e); return null; } if (url != null && info != null && info.length == 1 && info[0].inputStream != null) { try { info[0].inputStream.close(); } catch (IOException e) { } try { info[0].inputStream = new URL(url).openStream(); } catch (Exception e) { IJ.error("Open TIFF", "" + e); return null; } } return openTiff2(info); }
public Zipper<Map<Integer, MZipper<RoiContainer>>> exec( Zipper<Map<Integer, MZipper<RoiContainer>>> z, int frame) { JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(WindowManager.getCurrentWindow().getCanvas()); Map<Integer, MZipper<RoiContainer>> newRois; if (returnVal == JFileChooser.APPROVE_OPTION) { try { FileInputStream f = new FileInputStream(fc.getSelectedFile().getCanonicalPath()); MroiLisp parser = new MroiLisp(f); parser.ReInit(f); newRois = parser.roiFile(); // z.rights.clear(); // z.rights.add(newRois); // z = z.right(); // return z; return z.insertAndStep(newRois); } catch (IOException e) { IJ.error("Couldn't open from " + fc.getSelectedFile().getName() + ": " + e.getMessage()); } catch (mroi.ParseException e) { IJ.error("Failed in parsing: " + e.getMessage()); } catch (Exception e) { IJ.error("Malformed input file: " + e.getMessage()); } } return z; }
public void drop(DropTargetDropEvent dtde) { dtde.acceptDrop(DnDConstants.ACTION_COPY); DataFlavor[] flavors = null; try { Transferable t = dtde.getTransferable(); iterator = null; flavors = t.getTransferDataFlavors(); if (IJ.debugMode) IJ.log("DragAndDrop.drop: " + flavors.length + " flavors"); for (int i = 0; i < flavors.length; i++) { if (IJ.debugMode) IJ.log(" flavor[" + i + "]: " + flavors[i].getMimeType()); if (flavors[i].isFlavorJavaFileListType()) { Object data = t.getTransferData(DataFlavor.javaFileListFlavor); iterator = ((List) data).iterator(); break; } else if (flavors[i].isFlavorTextType()) { Object ob = t.getTransferData(flavors[i]); if (!(ob instanceof String)) continue; String s = ob.toString().trim(); if (IJ.isLinux() && s.length() > 1 && (int) s.charAt(1) == 0) s = fixLinuxString(s); ArrayList list = new ArrayList(); if (s.indexOf("href=\"") != -1 || s.indexOf("src=\"") != -1) { s = parseHTML(s); if (IJ.debugMode) IJ.log(" url: " + s); list.add(s); this.iterator = list.iterator(); break; } BufferedReader br = new BufferedReader(new StringReader(s)); String tmp; while (null != (tmp = br.readLine())) { tmp = java.net.URLDecoder.decode(tmp.replaceAll("\\+", "%2b"), "UTF-8"); if (tmp.startsWith("file://")) tmp = tmp.substring(7); if (IJ.debugMode) IJ.log(" content: " + tmp); if (tmp.startsWith("http://")) list.add(s); else list.add(new File(tmp)); } this.iterator = list.iterator(); break; } } if (iterator != null) { Thread thread = new Thread(this, "DrawAndDrop"); thread.setPriority(Math.max(thread.getPriority() - 1, Thread.MIN_PRIORITY)); thread.start(); } } catch (Exception e) { dtde.dropComplete(false); return; } dtde.dropComplete(true); if (flavors == null || flavors.length == 0) { if (IJ.isMacOSX()) IJ.error( "First drag and drop ignored. Please try again. You can avoid this\n" + "problem by dragging to the toolbar instead of the status bar."); else IJ.error("Drag and drop failed"); } }
public boolean beadCalibration3d() { imp = IJ.getImage(); if (imp == null) { IJ.noImage(); return false; } else if (imp.getStackSize() == 1) { IJ.error("Stack required"); return false; } else if (imp.getType() != ImagePlus.GRAY8 && imp.getType() != ImagePlus.GRAY16) { // In order to support 32bit images, pict[] must be changed to float[], and getPixel(x, y); // requires a Float.intBitsToFloat() conversion IJ.error("8 or 16 bit greyscale image required"); return false; } width = imp.getWidth(); height = imp.getHeight(); nslices = imp.getStackSize(); imtitle = imp.getTitle(); models[0] = "*None*"; models[1] = "line"; models[2] = "2nd degree polynomial"; models[3] = "3rd degree polynomial"; models[4] = "4th degree polynomial"; GenericDialog gd = new GenericDialog("3D PALM calibration"); gd.addNumericField("Maximum FWHM (in px)", prefs.get("QuickPALM.3Dcal_fwhm", 20), 0); gd.addNumericField( "Particle local threshold (% maximum intensity)", prefs.get("QuickPALM.pthrsh", 20), 0); gd.addNumericField("Z-spacing (nm)", prefs.get("QuickPALM.z-step", 10), 2); gd.addNumericField("Calibration Z-smoothing (radius)", prefs.get("QuickPALM.window", 1), 0); gd.addChoice("Model", models, prefs.get("QuickPALM.model", models[3])); gd.addCheckbox( "Show divergence of bead positions against model", prefs.get("QuickPALM.3Dcal_showDivergence", false)); gd.addCheckbox("Show extra particle info", prefs.get("QuickPALM.3Dcal_showExtraInfo", false)); gd.addMessage("\n\nDon't forget to save the table in the end..."); gd.showDialog(); if (gd.wasCanceled()) return false; fwhm = gd.getNextNumber(); prefs.set("QuickPALM.QuickPALM.3Dcal_fwhm", fwhm); pthrsh = gd.getNextNumber() / 100; prefs.set("QuickPALM.pthrsh", pthrsh * 100); cal_z = gd.getNextNumber(); prefs.set("QuickPALM.z-step", cal_z); window = (int) gd.getNextNumber(); prefs.set("QuickPALM.window", window); model = gd.getNextChoice(); prefs.set("QuickPALM.model", model); part_divergence = gd.getNextBoolean(); prefs.set("QuickPALM.3Dcal_showDivergence", part_divergence); part_extrainfo = gd.getNextBoolean(); prefs.set("QuickPALM.3Dcal_showExtraInfo", part_extrainfo); return true; }
/** Performs actual projection using specified method. */ public void doProjection() { if (imp == null) return; sliceCount = 0; if (method < AVG_METHOD || method > MEDIAN_METHOD) method = AVG_METHOD; for (int slice = startSlice; slice <= stopSlice; slice += increment) sliceCount++; if (method == MEDIAN_METHOD) { projImage = doMedianProjection(); return; } // Create new float processor for projected pixels. FloatProcessor fp = new FloatProcessor(imp.getWidth(), imp.getHeight()); ImageStack stack = imp.getStack(); RayFunction rayFunc = getRayFunction(method, fp); if (IJ.debugMode == true) { IJ.log("\nProjecting stack from: " + startSlice + " to: " + stopSlice); } // Determine type of input image. Explicit determination of // processor type is required for subsequent pixel // manipulation. This approach is more efficient than the // more general use of ImageProcessor's getPixelValue and // putPixel methods. int ptype; if (stack.getProcessor(1) instanceof ByteProcessor) ptype = BYTE_TYPE; else if (stack.getProcessor(1) instanceof ShortProcessor) ptype = SHORT_TYPE; else if (stack.getProcessor(1) instanceof FloatProcessor) ptype = FLOAT_TYPE; else { IJ.error("Z Project", "Non-RGB stack required"); return; } // Do the projection. for (int n = startSlice; n <= stopSlice; n += increment) { IJ.showStatus("ZProjection " + color + ": " + n + "/" + stopSlice); IJ.showProgress(n - startSlice, stopSlice - startSlice); projectSlice(stack.getPixels(n), rayFunc, ptype); } // Finish up projection. if (method == SUM_METHOD) { fp.resetMinAndMax(); projImage = new ImagePlus(makeTitle(), fp); } else if (method == SD_METHOD) { rayFunc.postProcess(); fp.resetMinAndMax(); projImage = new ImagePlus(makeTitle(), fp); } else { rayFunc.postProcess(); projImage = makeOutputImage(imp, fp, ptype); } if (projImage == null) IJ.error("Z Project", "Error computing projection."); }
void loadParticleResults(String filename, ResultsTable res) { try { String line; FileReader fr = new FileReader(filename); BufferedReader br = new BufferedReader(fr); java.lang.String header = " Intensity X (px) Y (px) X (nm) Y (nm) Z (nm) Left-Width(px) Right-Width (px) Up-Height (px) Down-Height (px) X Symmetry (%) Y Symmetry (%) Width minus Height (px) Frame Number"; java.lang.String firstline = br.readLine(); if (!firstline.contains("X (px) Y (px) X (nm) Y (nm) Z (nm)")) { IJ.error("File does not seam to be a Particles Table file"); IJ.log("Found header: " + firstline); IJ.log("Expecting: " + header); return; } res.reset(); int counter = 1; java.util.concurrent.locks.Lock lock = new java.util.concurrent.locks.ReentrantLock(); ThreadedLoader tloader = new ThreadedLoader(); // java.lang.String txt = fr.read(); while ((line = br.readLine()) != null) { tloader = new ThreadedLoader(); tloader.mysetup(res, lock, line); tloader.start(); IJ.showStatus("Loading particle " + counter + "... sit back and relax."); counter++; } try { tloader.join(); } catch (Exception e) { IJ.error("" + e); } if (res.getCounter() < 5000000) { IJ.showStatus("Creating particle table, this should take a few seconds..."); res.show("Results"); } else IJ.showMessage( "Warning", "Results table has too many particles, they will not be shown but the data still exists within it\nyou can still use all the plugin functionality or save table changes though the 'Save Particle Table' command."); fr.close(); IJ.showStatus("Done loading table..."); } catch (FileNotFoundException e) { IJ.error("File not found exception" + e); return; } catch (IOException e) { IJ.error("IOException exception" + e); return; } catch (NumberFormatException e) { IJ.error("Number format exception" + e); return; } }
/** Opens the nth image of the specified TIFF stack. */ public ImagePlus openTiff(String path, int n) { TiffDecoder td = new TiffDecoder(getDir(path), getName(path)); if (IJ.debugMode) td.enableDebugging(); FileInfo[] info = null; try { info = td.getTiffInfo(); } catch (IOException e) { String msg = e.getMessage(); if (msg == null || msg.equals("")) msg = "" + e; IJ.error("Open TIFF", msg); return null; } if (info == null) return null; FileInfo fi = info[0]; if (info.length == 1 && fi.nImages > 1) { if (n < 1 || n > fi.nImages) throw new IllegalArgumentException("N out of 1-" + fi.nImages + " range"); long size = fi.width * fi.height * fi.getBytesPerPixel(); fi.longOffset = fi.getOffset() + (n - 1) * (size + fi.gapBetweenImages); fi.offset = 0; fi.nImages = 1; } else { if (n < 1 || n > info.length) throw new IllegalArgumentException("N out of 1-" + info.length + " range"); fi.longOffset = info[n - 1].getOffset(); fi.offset = 0; fi.stripOffsets = info[n - 1].stripOffsets; fi.stripLengths = info[n - 1].stripLengths; } FileOpener fo = new FileOpener(fi); return fo.open(false); }
void createEllipse(ImagePlus imp) { IJ.showStatus("Fitting ellipse"); Roi roi = imp.getRoi(); if (roi == null) { noRoi("Fit Ellipse"); return; } if (roi.isLine()) { IJ.error("Fit Ellipse", "\"Fit Ellipse\" does not work with line selections"); return; } ImageProcessor ip = imp.getProcessor(); ip.setRoi(roi); int options = Measurements.CENTROID + Measurements.ELLIPSE; ImageStatistics stats = ImageStatistics.getStatistics(ip, options, null); double dx = stats.major * Math.cos(stats.angle / 180.0 * Math.PI) / 2.0; double dy = -stats.major * Math.sin(stats.angle / 180.0 * Math.PI) / 2.0; double x1 = stats.xCentroid - dx; double x2 = stats.xCentroid + dx; double y1 = stats.yCentroid - dy; double y2 = stats.yCentroid + dy; double aspectRatio = stats.minor / stats.major; imp.killRoi(); imp.setRoi(new EllipseRoi(x1, y1, x2, y2, aspectRatio)); }
public int showDialog(ImagePlus imp, String command, PlugInFilterRunner pfr) { if (doOptions) { this.imp = imp; this.pfr = pfr; GenericDialog gd = new GenericDialog("Binary Options"); gd.addNumericField("Iterations (1-" + MAX_ITERATIONS + "):", iterations, 0, 3, ""); gd.addNumericField("Count (1-8):", count, 0, 3, ""); gd.addCheckbox("Black background", Prefs.blackBackground); gd.addCheckbox("Pad edges when eroding", Prefs.padEdges); gd.addChoice("EDM output:", outputTypes, outputTypes[EDM.getOutputType()]); if (imp != null) { gd.addChoice("Do:", operations, operation); gd.addPreviewCheckbox(pfr); gd.addDialogListener(this); previewing = true; } gd.addHelp(IJ.URL + "/docs/menus/process.html#options"); gd.showDialog(); previewing = false; if (gd.wasCanceled()) return DONE; if (imp == null) { // options dialog only, no do/preview dialogItemChanged(gd, null); // read dialog result return DONE; } return operation.equals(NO_OPERATION) ? DONE : IJ.setupDialog(imp, flags); } else { // no dialog, 'arg' is operation type if (!((ByteProcessor) imp.getProcessor()).isBinary()) { IJ.error("8-bit binary (black and white only) image required."); return DONE; } return IJ.setupDialog(imp, flags); } }
/** * Logs an error message to either standard error stream of to ImageJ error function * * @param s error message */ public static void error(String s) { if (mode == BATCH) { System.err.println(s); } else { IJ.error(s); } }
ImagePlus openUsingImageIO(String path) { ImagePlus imp = null; BufferedImage img = null; File f = new File(path); try { img = ImageIO.read(f); } catch (Exception e) { IJ.error("Open Using ImageIO", "" + e); } if (img == null) return null; if (img.getColorModel().hasAlpha()) { int width = img.getWidth(); int height = img.getHeight(); BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics g = bi.getGraphics(); g.setColor(Color.white); g.fillRect(0, 0, width, height); g.drawImage(img, 0, 0, null); img = bi; } imp = new ImagePlus(f.getName(), img); FileInfo fi = new FileInfo(); fi.fileFormat = fi.IMAGEIO; fi.fileName = f.getName(); fi.directory = f.getParent() + File.separator; imp.setFileInfo(fi); return imp; }
/** * Prepare for processing; also called at the very end with argument 'final' to show any newly * created output image. */ public int setup(String arg, ImagePlus imp) { if (arg.equals("final")) { showOutput(); return DONE; } this.imp = imp; // 'arg' is processing type; default is 'EDM' (0) if (arg.equals("watershed")) { processType = WATERSHED; flags += KEEP_THRESHOLD; } else if (arg.equals("points")) processType = UEP; else if (arg.equals("voronoi")) processType = VORONOI; // output type if (processType != WATERSHED) // Watershed always has output BYTE_OVERWRITE=0 outImageType = outputType; // otherwise use the static variable from setOutputType if (outImageType != BYTE_OVERWRITE) flags |= NO_CHANGES; // check image and prepare if (imp != null) { ImageProcessor ip = imp.getProcessor(); if (!ip.isBinary()) { IJ.error("8-bit binary image (0 and 255) required."); return DONE; } ip.resetRoi(); // processing routines assume background=0; image may be otherwise boolean invertedLut = imp.isInvertedLut(); background255 = (invertedLut && Prefs.blackBackground) || (!invertedLut && !Prefs.blackBackground); } return flags; } // public int setup
public int setup(String arg, ImagePlus imp) { this.arg = arg; this.imp = imp; IJ.register(ParticleAnalyzer.class); if (imp == null) { IJ.noImage(); return DONE; } if (imp.getBitDepth() == 24 && !isThresholdedRGB(imp)) { IJ.error( "Particle Analyzer", "RGB images must be thresholded using\n" + "Image>Adjust>Color Threshold."); return DONE; } if (!showDialog()) return DONE; int baseFlags = DOES_ALL + NO_CHANGES + NO_UNDO; int flags = IJ.setupDialog(imp, baseFlags); processStack = (flags & DOES_STACKS) != 0; slice = 0; saveRoi = imp.getRoi(); if (saveRoi != null && saveRoi.getType() != Roi.RECTANGLE && saveRoi.isArea()) polygon = saveRoi.getPolygon(); imp.startTiming(); nextFontSize = defaultFontSize; nextLineWidth = 1; return flags; }
/** Returns the index of the selected item in the next popup menu. */ public int getNextChoiceIndex() { if (choice == null) return -1; Choice thisChoice = (Choice) (choice.elementAt(choiceIndex)); int index = thisChoice.getSelectedIndex(); if (macro) { String label = (String) labels.get((Object) thisChoice); String oldItem = thisChoice.getSelectedItem(); int oldIndex = thisChoice.getSelectedIndex(); String item = Macro.getValue(macroOptions, label, oldItem); if (item != null && item.startsWith("&")) // value is macro variable item = getChoiceVariable(item); thisChoice.select(item); index = thisChoice.getSelectedIndex(); if (index == oldIndex && !item.equals(oldItem)) { // is value a macro variable? Interpreter interp = Interpreter.getInstance(); String s = interp != null ? interp.getStringVariable(item) : null; if (s == null) IJ.error(getTitle(), "\"" + item + "\" is not a valid choice for \"" + label + "\""); else item = s; } } if (recorderOn) { int defaultIndex = ((Integer) (defaultChoiceIndexes.elementAt(choiceIndex))).intValue(); if (!(smartRecording && index == defaultIndex)) { String item = thisChoice.getSelectedItem(); if (!(item.equals("*None*") && getTitle().equals("Merge Channels"))) recordOption(thisChoice, thisChoice.getSelectedItem()); } } choiceIndex++; return index; }
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) { IJ.error("Rotate>Selection", "This command requires a 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; } }
public boolean checkBeads() { rmanager = RoiManager.getInstance(); if (IJ.versionLessThan("1.26i")) return false; else if (rmanager == null) { IJ.error("Add bead ROIs to the RoiManager first (select region then press [t])."); return false; } nrois = rmanager.getCount(); if (nrois == 0) { IJ.error("Add bead ROIs to the RoiManager first (select region then press [t])."); return false; } rois = rmanager.getRoisAsArray(); return true; }
void lineToArea(ImagePlus imp) { Roi roi = imp.getRoi(); if (roi == null || !roi.isLine()) { IJ.error("Line to Area", "Line selection required"); return; } Undo.setup(Undo.ROI, imp); Roi roi2 = null; if (roi.getType() == Roi.LINE) { double width = roi.getStrokeWidth(); if (width <= 1.0) roi.setStrokeWidth(1.0000001); FloatPolygon p = roi.getFloatPolygon(); roi.setStrokeWidth(width); roi2 = new PolygonRoi(p, Roi.POLYGON); roi2.setDrawOffset(roi.getDrawOffset()); } else { ImageProcessor ip2 = new ByteProcessor(imp.getWidth(), imp.getHeight()); ip2.setColor(255); roi.drawPixels(ip2); // new ImagePlus("ip2", ip2.duplicate()).show(); ip2.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE); ThresholdToSelection tts = new ThresholdToSelection(); roi2 = tts.convert(ip2); } transferProperties(roi, roi2); roi2.setStrokeWidth(0); Color c = roi2.getStrokeColor(); if (c != null) // remove any transparency roi2.setStrokeColor(new Color(c.getRed(), c.getGreen(), c.getBlue())); imp.setRoi(roi2); Roi.previousRoi = (Roi) roi.clone(); }
public IntPair getDataPosition(int ranking0) { // ascending, ranking starts from 0 if (ranking0 >= m_nSize) { IJ.error("ranking is larger than the data size: in getDataPosition"); return null; } IntPair ip = null; int r, c, num = m_dvDataLo.size(), nt; ArrayList<Double> dvt; dvt = m_dvDataLo; nt = dvt.size(); num = nt; r = -1; while (num <= ranking0) { r++; if (r < m_nDim) dvt = m_pdvData[r]; else dvt = m_dvDataHi; nt = dvt.size(); num += nt; } if (r >= m_nDim) r = -2; int ranking = ranking0 - (num - nt); c = CommonStatisticsMethods.getRankingIndex(dvt, ranking, 1); ip = new IntPair(r, c); return ip; }
/** * Opens a single TIFF or DICOM contained in a ZIP archive, or a ZIPed collection of ".roi" files * created by the ROI manager. */ public ImagePlus openZip(String path) { ImagePlus imp = null; try { ZipInputStream zis = new ZipInputStream(new FileInputStream(path)); ZipEntry entry = zis.getNextEntry(); if (entry == null) { zis.close(); return null; } String name = entry.getName(); if (name.endsWith(".roi")) { zis.close(); if (!silentMode) if (IJ.isMacro() && Interpreter.isBatchMode() && RoiManager.getInstance() == null) IJ.log( "Use roiManager(\"Open\", path) instead of open(path)\nto open ROI sets in batch mode macros."); else IJ.runMacro("roiManager(\"Open\", getArgument());", path); return null; } if (name.endsWith(".tif")) { imp = openTiff(zis, name); } else if (name.endsWith(".dcm")) { DICOM dcm = new DICOM(zis); dcm.run(name); imp = dcm; } else { zis.close(); IJ.error( "Opener", "This ZIP archive does not appear to contain a \nTIFF (\".tif\") or DICOM (\".dcm\") file, or ROIs (\".roi\")."); return null; } zis.close(); } catch (Exception e) { IJ.error("Opener", "" + e); return null; } File f = new File(path); FileInfo fi = imp.getOriginalFileInfo(); if (fi != null) { fi.fileFormat = FileInfo.ZIP_ARCHIVE; fi.fileName = f.getName(); fi.directory = f.getParent() + File.separator; } return imp; }
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); }
/** Opens a tab or comma delimited text file in the Results window. */ public static void openResultsTable(String path) { try { ResultsTable rt = ResultsTable.open(path); if (rt != null) rt.show("Results"); } catch (IOException e) { IJ.error("Open Results", e.getMessage()); } }
public void run(String arg) { if (!LibraryChecker.checkImageJ()) return; if (!IJ.macroRunning()) { IJ.error("Cannot install extensions from outside a macro."); return; } Functions.registerExtensions(this); }
boolean setProperties(String title, Roi roi) { Frame f = WindowManager.getFrontWindow(); if (f != null && f.getTitle().indexOf("3D Viewer") != -1) return false; if (roi == null) { IJ.error("This command requires a selection."); return false; } RoiProperties rp = new RoiProperties(title, roi); return rp.showDialog(); }
byte[] download(File f) { if (!f.exists()) { IJ.error("Plugin Installer", "File not found: " + f); return null; } byte[] data = null; try { int len = (int) f.length(); InputStream in = new BufferedInputStream(new FileInputStream(f)); DataInputStream dis = new DataInputStream(in); data = new byte[len]; dis.readFully(data); dis.close(); } catch (Exception e) { IJ.error("Plugin Installer", "" + e); data = null; } return data; }
boolean savePlugin(File f, byte[] data) { try { FileOutputStream out = new FileOutputStream(f); out.write(data, 0, data.length); out.close(); } catch (IOException e) { IJ.error("Plugin Installer", "" + e); return false; } return true; }
void fromRoiManager() { ImagePlus imp = IJ.getImage(); RoiManager rm = RoiManager.getInstance(); if (rm == null) { IJ.error("ROI Manager is not open"); return; } Roi[] rois = rm.getRoisAsArray(); if (rois.length == 0) { IJ.error("ROI Manager is empty"); return; } Overlay overlay = new Overlay(); for (int i = 0; i < rois.length; i++) overlay.add((Roi) rois[i].clone()); imp.setOverlay(overlay); ImageCanvas ic = imp.getCanvas(); if (ic != null) ic.setShowAllROIs(false); rm.setEditMode(imp, false); imp.killRoi(); }