protected void hideRois() { if (currentImage == null) return; currentImage.killRoi(); if (currentImage.isVisible()) { currentImage.updateAndDraw(); ImageUtils.removeScrollListener(currentImage, this, this); } currentImage = null; }
protected void updateRoi() { // System.out.println("image:"+currentImage.getTitle()+ " slice:"+currentImage.getSlice()); Roi r = currentROIs.get(currentImage.getSlice()); if (r != null) { currentImage.setRoi(r); } else { currentImage.killRoi(); } currentImage.updateAndDraw(); }
private boolean ignoreArrowKeys(ImagePlus imp) { Frame frame = WindowManager.getFrontWindow(); String title = frame.getTitle(); if (title != null && title.equals("ROI Manager")) return true; // Control Panel? if (frame != null && frame instanceof javax.swing.JFrame) return true; ImageWindow win = imp.getWindow(); // LOCI Data Browser window? if (imp.getStackSize() > 1 && win != null && win.getClass().getName().startsWith("loci")) return true; return false; }
/** * Attempts to open the specified path with the given plugin. If the plugin extends the ImagePlus * class (e.g., BioRad_Reader), set extendsImagePlus to true, otherwise (e.g., LSM_Reader) set it * to false. * * @return A reference to the plugin, if it was successful. */ private Object tryPlugIn(String className, String path) { Object o = IJ.runPlugIn(className, path); if (o instanceof ImagePlus) { // plugin extends ImagePlus class ImagePlus imp = (ImagePlus) o; if (imp.getWidth() == 0) o = null; // invalid image else width = IMAGE_OPENED; // success } else { // plugin does not extend ImagePlus; assume success width = IMAGE_OPENED; } return o; }
void setStackDisplayRange(ImagePlus imp) { ImageStack stack = imp.getStack(); double min = Double.MAX_VALUE; double max = -Double.MAX_VALUE; int n = stack.getSize(); for (int i = 1; i <= n; i++) { if (!silentMode) IJ.showStatus("Calculating stack min and max: " + i + "/" + n); ImageProcessor ip = stack.getProcessor(i); ip.resetMinAndMax(); if (ip.getMin() < min) min = ip.getMin(); if (ip.getMax() > max) max = ip.getMax(); } imp.getProcessor().setMinAndMax(min, max); imp.updateAndDraw(); }
/** Opens a stack of images. */ ImagePlus openStack(ColorModel cm, boolean show) { ImageStack stack = new ImageStack(fi.width, fi.height, cm); long skip = fi.getOffset(); Object pixels; try { ImageReader reader = new ImageReader(fi); InputStream is = createInputStream(fi); if (is == null) return null; IJ.resetEscape(); for (int i = 1; i <= fi.nImages; i++) { if (!silentMode) IJ.showStatus("Reading: " + i + "/" + fi.nImages); if (IJ.escapePressed()) { IJ.beep(); IJ.showProgress(1.0); silentMode = false; return null; } pixels = reader.readPixels(is, skip); if (pixels == null) break; stack.addSlice(null, pixels); skip = fi.gapBetweenImages; if (!silentMode) IJ.showProgress(i, fi.nImages); } is.close(); } catch (Exception e) { IJ.log("" + e); } catch (OutOfMemoryError e) { IJ.outOfMemory(fi.fileName); stack.trim(); } if (!silentMode) IJ.showProgress(1.0); if (stack.getSize() == 0) return null; if (fi.sliceLabels != null && fi.sliceLabels.length <= stack.getSize()) { for (int i = 0; i < fi.sliceLabels.length; i++) stack.setSliceLabel(fi.sliceLabels[i], i + 1); } ImagePlus imp = new ImagePlus(fi.fileName, stack); if (fi.info != null) imp.setProperty("Info", fi.info); if (show) imp.show(); imp.setFileInfo(fi); setCalibration(imp); ImageProcessor ip = imp.getProcessor(); if (ip.getMin() == ip.getMax()) // find stack min and max if first slice is blank setStackDisplayRange(imp); if (!silentMode) IJ.showProgress(1.0); silentMode = false; return imp; }
protected void registerActiveImage() { ImagePlus activeImage = WindowManager.getCurrentImage(); if (activeImage != null && activeImage.getProcessor() != null) { // && activeImage.getImageStackSize() > 1 if (currentImage != null && currentImage.getWindow() != null && currentImage != activeImage) { // System.out.println("remove listener:"+currentImage.getTitle()); ImageUtils.removeScrollListener(currentImage, this, this); currentImage.killRoi(); currentImage.updateAndDraw(); currentImage = null; } if (currentImage != activeImage) { // System.out.println("add listener:"+activeImage.getTitle()); ImageUtils.addScrollListener(activeImage, this, this); this.currentImage = activeImage; } } }
void checkForCalibrationConflict(ImagePlus imp, Calibration cal) { Calibration gcal = imp.getGlobalCalibration(); if (gcal == null || !showConflictMessage || IJ.isMacro()) return; if (cal.pixelWidth == gcal.pixelWidth && cal.getUnit().equals(gcal.getUnit())) return; GenericDialog gd = new GenericDialog(imp.getTitle()); gd.addMessage("The calibration of this image conflicts\nwith the current global calibration."); gd.addCheckbox("Disable_Global Calibration", true); gd.addCheckbox("Disable_these Messages", false); gd.showDialog(); if (gd.wasCanceled()) return; boolean disable = gd.getNextBoolean(); if (disable) { imp.setGlobalCalibration(null); imp.setCalibration(cal); WindowManager.repaintImageWindows(); } boolean dontShow = gd.getNextBoolean(); if (dontShow) showConflictMessage = false; }
private boolean showDialog() { String[] types = {"RAW", "JPEG", "ZLIB"}; GenericDialog gd = new GenericDialog("Generate Bricks"); gd.addChoice("FileType", types, filetype); gd.addNumericField("JPEG quality", jpeg_quality, 0); gd.addNumericField("Max file size (MB)", bdsizelimit, 0); int[] wlist = WindowManager.getIDList(); if (wlist == null) return false; String[] titles = new String[wlist.length]; for (int i = 0; i < wlist.length; i++) titles[i] = ""; int tnum = 0; for (int i = 0; i < wlist.length; i++) { ImagePlus imp = WindowManager.getImage(wlist[i]); if (imp != null) { titles[tnum] = imp.getTitle(); tnum++; } } gd.addChoice("Source image: ", titles, titles[0]); gd.showDialog(); if (gd.wasCanceled()) return false; filetype = types[gd.getNextChoiceIndex()]; jpeg_quality = (int) gd.getNextNumber(); if (jpeg_quality > 100) jpeg_quality = 100; if (jpeg_quality < 0) jpeg_quality = 0; bdsizelimit = (int) gd.getNextNumber(); int id = gd.getNextChoiceIndex(); lvImgTitle = new ArrayList<String>(); lvImgTitle.add(titles[id]); Prefs.set("filetype.string", filetype); Prefs.set("jpeg_quality.int", jpeg_quality); Prefs.set("bdsizelimit.int", bdsizelimit); return true; }
private boolean deleteOverlayRoi(ImagePlus imp) { if (imp == null) return false; Overlay overlay = null; ImageCanvas ic = imp.getCanvas(); if (ic != null) overlay = ic.getShowAllList(); if (overlay == null) overlay = imp.getOverlay(); if (overlay == null) return false; Roi roi = imp.getRoi(); for (int i = 0; i < overlay.size(); i++) { Roi roi2 = overlay.get(i); if (roi2 == roi) { overlay.remove(i); imp.deleteRoi(); ic = imp.getCanvas(); if (ic != null) ic.roiManagerSelect(roi, true); return true; } } return false; }
void abortPluginOrMacro(ImagePlus imp) { if (imp != null) { ImageWindow win = imp.getWindow(); if (win != null) { win.running = false; win.running2 = false; } } Macro.abort(); Interpreter.abort(); if (Interpreter.getInstance() != null) IJ.beep(); }
public void deleteSelectedObjects() { populatingObjects = true; try { boolean[] modif = new boolean[currentChannels.length]; for (Object o : this.list.getSelectedValues()) { listModel.removeElement(o); modif[getChannelRank(((Object3DGui) o).getChannel())] = true; ((Object3DGui) o).delete(true); } for (int i = 0; i < currentChannels.length; i++) { if (modif[i]) { ImagePlus img = currentChannels[i].getSegmented().getImagePlus(); if (img.isVisible()) { img.updateAndDraw(); } currentChannels[i].createObjects(); if (autoSave) currentChannels[i].saveOutput(); } } } catch (Exception e) { exceptionPrinter.print(e, "", Core.GUIMode); } populatingObjects = false; }
public void mergeSelectedObjects() { this.populatingObjects = true; HashMap<Integer, ArrayList<Object3DGui>> allObjects = getSplitSelection(); for (int channelIdx : allObjects.keySet()) { ArrayList<Object3DGui> objects = allObjects.get(channelIdx); if (objects != null && objects.size() >= 2) { Collections.sort(objects); Object3DGui o1 = objects.get(0); for (int i = objects.size() - 1; i > 0; i--) { Object3DGui o2 = objects.get(i); o1.merge(o2); listModel.removeElement(o2); // IJ.log("merge:"+o1.getName()+ "::"+objects.get(i).getName()+ " channel:"+channelIdx); } o1.getChannel().createObjects(); if (autoSave) o1.getChannel().saveOutput(); ImagePlus img = o1.getChannel().getSegmented().getImagePlus(); if (img.isVisible()) { img.updateAndDraw(); } } } this.populatingObjects = false; }
public void showRois3D() { registerActiveImage(); if (currentImage == null) return; // verifier que l'image active a les memes dimentions Object[] os = this.list.getSelectedValues(); if (os.length == 1) { mcib3d.geom.Object3D o = ((Object3DGui) os[0]).getObject3D(); currentImage.setSlice((o.getZmax() + o.getZmin()) / 2 + 1); } int nSlices = currentImage.getNSlices(); currentROIs = new HashMap<Integer, Roi>(nSlices); // stores the roi mask to save memory.. if (roiMask == null || !roiMask.sameDimentions(currentImage)) { roiMask = new ImageByte("mask", currentImage.getWidth(), currentImage.getHeight(), nSlices); } else { roiMask.erase(); } ImageStack maskStack = roiMask.getImageStack(); Object3DGui obj; for (Object o : os) { obj = (Object3DGui) o; obj.getObject3D().draw(maskStack, 255); } // roiMask.show(); for (int i = 1; i <= nSlices; i++) { ImagePlus im = new ImagePlus("mask", maskStack.getProcessor(i)); im.getProcessor().setThreshold(1, 255, ImageProcessor.NO_LUT_UPDATE); ThresholdToSelection tts = new ThresholdToSelection(); tts.setup("", im); tts.run(im.getProcessor()); Roi r = im.getRoi(); if (r != null) currentROIs.put(i, r); } updateRoi(); }
public void keyPressed(KeyEvent e) { // if (e.isConsumed()) return; int keyCode = e.getKeyCode(); IJ.setKeyDown(keyCode); hotkey = false; if (keyCode == KeyEvent.VK_CONTROL || keyCode == KeyEvent.VK_SHIFT) return; char keyChar = e.getKeyChar(); int flags = e.getModifiers(); if (IJ.debugMode) IJ.log( "keyPressed: code=" + keyCode + " (" + KeyEvent.getKeyText(keyCode) + "), char=\"" + keyChar + "\" (" + (int) keyChar + "), flags=" + KeyEvent.getKeyModifiersText(flags)); boolean shift = (flags & KeyEvent.SHIFT_MASK) != 0; boolean control = (flags & KeyEvent.CTRL_MASK) != 0; boolean alt = (flags & KeyEvent.ALT_MASK) != 0; boolean meta = (flags & KeyEvent.META_MASK) != 0; String cmd = null; ImagePlus imp = WindowManager.getCurrentImage(); boolean isStack = (imp != null) && (imp.getStackSize() > 1); if (imp != null && !control && ((keyChar >= 32 && keyChar <= 255) || keyChar == '\b' || keyChar == '\n')) { Roi roi = imp.getRoi(); if (roi instanceof TextRoi) { if ((flags & KeyEvent.META_MASK) != 0 && IJ.isMacOSX()) return; if (alt) { switch (keyChar) { case 'u': case 'm': keyChar = IJ.micronSymbol; break; case 'A': keyChar = IJ.angstromSymbol; break; default: } } ((TextRoi) roi).addChar(keyChar); return; } } // Handle one character macro shortcuts if (!control && !meta) { Hashtable macroShortcuts = Menus.getMacroShortcuts(); if (macroShortcuts.size() > 0) { if (shift) cmd = (String) macroShortcuts.get(new Integer(keyCode + 200)); else cmd = (String) macroShortcuts.get(new Integer(keyCode)); if (cmd != null) { // MacroInstaller.runMacroCommand(cmd); commandName = cmd; MacroInstaller.runMacroShortcut(cmd); return; } } } if ((!Prefs.requireControlKey || control || meta) && keyChar != '+') { Hashtable shortcuts = Menus.getShortcuts(); if (shift) cmd = (String) shortcuts.get(new Integer(keyCode + 200)); else cmd = (String) shortcuts.get(new Integer(keyCode)); } if (cmd == null) { switch (keyChar) { case '<': case ',': if (isStack) cmd = "Previous Slice [<]"; break; case '>': case '.': case ';': if (isStack) cmd = "Next Slice [>]"; break; case '+': case '=': cmd = "In [+]"; break; case '-': cmd = "Out [-]"; break; case '/': cmd = "Reslice [/]..."; break; default: } } if (cmd == null) { switch (keyCode) { case KeyEvent.VK_TAB: WindowManager.putBehind(); return; case KeyEvent.VK_BACK_SPACE: // delete if (deleteOverlayRoi(imp)) return; cmd = "Clear"; hotkey = true; break; // case KeyEvent.VK_BACK_SLASH: cmd=IJ.altKeyDown()?"Animation Options...":"Start // Animation"; break; case KeyEvent.VK_EQUALS: cmd = "In [+]"; break; case KeyEvent.VK_MINUS: cmd = "Out [-]"; break; case KeyEvent.VK_SLASH: case 0xbf: cmd = "Reslice [/]..."; break; case KeyEvent.VK_COMMA: case 0xbc: if (isStack) cmd = "Previous Slice [<]"; break; case KeyEvent.VK_PERIOD: case 0xbe: if (isStack) cmd = "Next Slice [>]"; break; case KeyEvent.VK_LEFT: case KeyEvent.VK_RIGHT: case KeyEvent.VK_UP: case KeyEvent.VK_DOWN: // arrow keys if (imp == null) return; Roi roi = imp.getRoi(); if (IJ.shiftKeyDown() && imp == Orthogonal_Views.getImage()) return; boolean stackKey = imp.getStackSize() > 1 && (roi == null || IJ.shiftKeyDown()); boolean zoomKey = roi == null || IJ.shiftKeyDown() || IJ.controlKeyDown(); if (stackKey && keyCode == KeyEvent.VK_RIGHT) cmd = "Next Slice [>]"; else if (stackKey && keyCode == KeyEvent.VK_LEFT) cmd = "Previous Slice [<]"; else if (zoomKey && keyCode == KeyEvent.VK_DOWN && !ignoreArrowKeys(imp) && Toolbar.getToolId() < Toolbar.SPARE6) cmd = "Out [-]"; else if (zoomKey && keyCode == KeyEvent.VK_UP && !ignoreArrowKeys(imp) && Toolbar.getToolId() < Toolbar.SPARE6) cmd = "In [+]"; else if (roi != null) { if ((flags & KeyEvent.ALT_MASK) != 0) roi.nudgeCorner(keyCode); else roi.nudge(keyCode); return; } break; case KeyEvent.VK_ESCAPE: abortPluginOrMacro(imp); return; case KeyEvent.VK_ENTER: WindowManager.toFront(this); return; default: break; } } if (cmd != null && !cmd.equals("")) { commandName = cmd; if (cmd.equals("Fill") || cmd.equals("Draw")) hotkey = true; if (cmd.charAt(0) == MacroInstaller.commandPrefix) MacroInstaller.runMacroShortcut(cmd); else { doCommand(cmd); keyPressedTime = System.currentTimeMillis(); lastKeyCommand = cmd; } } }
/** 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; } }
/** Called from io/Opener.java. */ public void run(String path) { if (path.equals("")) return; File theFile = new File(path); String directory = theFile.getParent(); String fileName = theFile.getName(); if (directory == null) directory = ""; // Try and recognise file type and load the file if recognised ImagePlus imp = openImage(directory, fileName, path); if (imp == null) { IJ.showStatus(""); return; // failed to load file or plugin has opened and displayed it } ImageStack stack = imp.getStack(); // get the title from the stack (falling back to the fileName) String title = imp.getTitle().equals("") ? fileName : imp.getTitle(); // set the stack of this HandleExtraFileTypes object // to that attached to the ImagePlus object returned by openImage() setStack(title, stack); // copy over the calibration info since it doesn't come with the ImageProcessor setCalibration(imp.getCalibration()); // also copy the Show Info field over if it exists if (imp.getProperty("Info") != null) setProperty("Info", imp.getProperty("Info")); // copy the FileInfo setFileInfo(imp.getOriginalFileInfo()); // copy dimensions if (IJ.getVersion().compareTo("1.38s") >= 0) setDimensions(imp.getNChannels(), imp.getNSlices(), imp.getNFrames()); if (IJ.getVersion().compareTo("1.41o") >= 0) setOpenAsHyperStack(imp.getOpenAsHyperStack()); }
void setCalibration(ImagePlus imp) { if (fi.fileType == FileInfo.GRAY16_SIGNED) { if (IJ.debugMode) IJ.log("16-bit signed"); double[] coeff = new double[2]; coeff[0] = -32768.0; coeff[1] = 1.0; imp.getLocalCalibration().setFunction(Calibration.STRAIGHT_LINE, coeff, "gray value"); } Properties props = decodeDescriptionString(fi); Calibration cal = imp.getCalibration(); boolean calibrated = false; if (fi.pixelWidth > 0.0 && fi.unit != null) { cal.pixelWidth = fi.pixelWidth; cal.pixelHeight = fi.pixelHeight; cal.pixelDepth = fi.pixelDepth; cal.setUnit(fi.unit); calibrated = true; } if (fi.valueUnit != null) { int f = fi.calibrationFunction; if ((f >= Calibration.STRAIGHT_LINE && f <= Calibration.RODBARD2 && fi.coefficients != null) || f == Calibration.UNCALIBRATED_OD) { boolean zeroClip = props != null && props.getProperty("zeroclip", "false").equals("true"); cal.setFunction(f, fi.coefficients, fi.valueUnit, zeroClip); calibrated = true; } } if (calibrated) checkForCalibrationConflict(imp, cal); if (fi.frameInterval != 0.0) cal.frameInterval = fi.frameInterval; if (props == null) return; cal.xOrigin = getDouble(props, "xorigin"); cal.yOrigin = getDouble(props, "yorigin"); cal.zOrigin = getDouble(props, "zorigin"); cal.info = props.getProperty("info"); cal.fps = getDouble(props, "fps"); cal.loop = getBoolean(props, "loop"); cal.frameInterval = getDouble(props, "finterval"); cal.setTimeUnit(props.getProperty("tunit", "sec")); double displayMin = getDouble(props, "min"); double displayMax = getDouble(props, "max"); if (!(displayMin == 0.0 && displayMax == 0.0)) { int type = imp.getType(); ImageProcessor ip = imp.getProcessor(); if (type == ImagePlus.GRAY8 || type == ImagePlus.COLOR_256) ip.setMinAndMax(displayMin, displayMax); else if (type == ImagePlus.GRAY16 || type == ImagePlus.GRAY32) { if (ip.getMin() != displayMin || ip.getMax() != displayMax) ip.setMinAndMax(displayMin, displayMax); } } int stackSize = imp.getStackSize(); if (stackSize > 1) { int channels = (int) getDouble(props, "channels"); int slices = (int) getDouble(props, "slices"); int frames = (int) getDouble(props, "frames"); if (channels == 0) channels = 1; if (slices == 0) slices = 1; if (frames == 0) frames = 1; // IJ.log("setCalibration: "+channels+" "+slices+" "+frames); if (channels * slices * frames == stackSize) { imp.setDimensions(channels, slices, frames); if (getBoolean(props, "hyperstack")) imp.setOpenAsHyperStack(true); } } }
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(); } }
/** Opens the image. Displays it if 'show' is true. Returns an ImagePlus object if successful. */ public ImagePlus open(boolean show) { ImagePlus imp = null; Object pixels; ProgressBar pb = null; ImageProcessor ip; ColorModel cm = createColorModel(fi); if (fi.nImages > 1) { return openStack(cm, show); } switch (fi.fileType) { case FileInfo.GRAY8: case FileInfo.COLOR8: case FileInfo.BITMAP: pixels = readPixels(fi); if (pixels == null) return null; ip = new ByteProcessor(width, height, (byte[]) pixels, cm); imp = new ImagePlus(fi.fileName, ip); break; case FileInfo.GRAY16_SIGNED: case FileInfo.GRAY16_UNSIGNED: case FileInfo.GRAY12_UNSIGNED: pixels = readPixels(fi); if (pixels == null) return null; ip = new ShortProcessor(width, height, (short[]) pixels, cm); imp = new ImagePlus(fi.fileName, ip); break; case FileInfo.GRAY32_INT: case FileInfo.GRAY32_UNSIGNED: case FileInfo.GRAY32_FLOAT: case FileInfo.GRAY24_UNSIGNED: case FileInfo.GRAY64_FLOAT: pixels = readPixels(fi); if (pixels == null) return null; ip = new FloatProcessor(width, height, (float[]) pixels, cm); imp = new ImagePlus(fi.fileName, ip); break; case FileInfo.RGB: case FileInfo.BGR: case FileInfo.ARGB: case FileInfo.ABGR: case FileInfo.BARG: case FileInfo.RGB_PLANAR: pixels = readPixels(fi); if (pixels == null) return null; ip = new ColorProcessor(width, height, (int[]) pixels); imp = new ImagePlus(fi.fileName, ip); break; case FileInfo.RGB48: case FileInfo.RGB48_PLANAR: boolean planar = fi.fileType == FileInfo.RGB48_PLANAR; Object[] pixelArray = (Object[]) readPixels(fi); if (pixelArray == null) return null; ImageStack stack = new ImageStack(width, height); stack.addSlice("Red", pixelArray[0]); stack.addSlice("Green", pixelArray[1]); stack.addSlice("Blue", pixelArray[2]); imp = new ImagePlus(fi.fileName, stack); imp.setDimensions(3, 1, 1); if (planar) imp.getProcessor().resetMinAndMax(); imp.setFileInfo(fi); int mode = CompositeImage.COMPOSITE; if (fi.description != null) { if (fi.description.indexOf("mode=color") != -1) mode = CompositeImage.COLOR; else if (fi.description.indexOf("mode=gray") != -1) mode = CompositeImage.GRAYSCALE; } imp = new CompositeImage(imp, mode); if (!planar && fi.displayRanges == null) { for (int c = 1; c <= 3; c++) { imp.setPosition(c, 1, 1); imp.setDisplayRange(minValue, maxValue); } imp.setPosition(1, 1, 1); } break; } imp.setFileInfo(fi); setCalibration(imp); if (fi.info != null) imp.setProperty("Info", fi.info); if (fi.sliceLabels != null && fi.sliceLabels.length == 1 && fi.sliceLabels[0] != null) imp.setProperty("Label", fi.sliceLabels[0]); if (show) imp.show(); return imp; }
public int setup(String arg, ImagePlus imp) { stack = imp.getStack(); return DOES_16; }