void reset(ImagePlus imp, ImageProcessor ip) { // Assign the pixels of ip to the data in the restore array, while // taking care to not give the address the restore array to the // image processor. int[] pixels = (int[]) ip.getPixels(); for (int i = 0; i < numPixels; i++) pixels[i] = restore[i]; }
/** 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; }
void setHistogram(ImagePlus imp, int j) { ImageProcessor ip = imp.getProcessor(); ImageStatistics stats = ImageStatistics.getStatistics(ip, AREA + MODE, null); int maxCount2 = 0; histogram = stats.histogram; for (int i = 0; i < stats.nBins; i++) if ((histogram[i] > maxCount2) && (i != stats.mode)) maxCount2 = histogram[i]; hmax = stats.maxCount; if ((hmax > (maxCount2 * 1.5)) && (maxCount2 != 0)) { // GL 1.5 was 2 hmax = (int) (maxCount2 * 1.1); // GL 1.1 was 1.5 histogram[stats.mode] = hmax; } os = null; ColorModel cm = ip.getColorModel(); if (!(cm instanceof IndexColorModel)) return; IndexColorModel icm = (IndexColorModel) cm; int mapSize = icm.getMapSize(); if (mapSize != 256) return; byte[] r = new byte[256]; byte[] g = new byte[256]; byte[] b = new byte[256]; icm.getReds(r); icm.getGreens(g); icm.getBlues(b); hColors = new Color[256]; if (isRGB) { if (j == 0) { for (int i = 0; i < 256; i++) hColors[i] = new Color(i & 255, 0 & 255, 0 & 255); } else if (j == 1) { for (int i = 0; i < 256; i++) hColors[i] = new Color(0 & 255, i & 255, 0 & 255); } else if (j == 2) { for (int i = 0; i < 256; i++) hColors[i] = new Color(0 & 255, 0 & 255, i & 255); } } else { if (j == 0) { for (int i = 0; i < 256; i++) hColors[i] = new Color(r[i] & 255, g[i] & 255, b[i] & 255); } else if (j == 1) { for (int i = 0; i < 256; i++) // hColors[i] = new Color(127-i/2&255, 127+i/2&255, 127-i/2&255); hColors[i] = new Color(192 - i / 4 & 255, 192 + i / 4 & 255, 192 - i / 4 & 255); } else if (j == 2) { for (int i = 0; i < 256; i++) hColors[i] = new Color(i & 255, i & 255, 0 & 255); } } }
void scale(ImageProcessor ip) { if (newWindow) { Rectangle r = ip.getRoi(); ImagePlus imp2 = imp.createImagePlus(); imp2.setProcessor(title, ip.resize(newWidth, newHeight)); Calibration cal = imp2.getCalibration(); if (cal.scaled()) { cal.pixelWidth *= 1.0 / xscale; cal.pixelHeight *= 1.0 / yscale; } imp2.show(); imp.trimProcessor(); imp2.trimProcessor(); imp2.changes = true; } else { if (processStack && imp.getStackSize() > 1) { Undo.reset(); StackProcessor sp = new StackProcessor(imp.getStack(), ip); sp.scale(xscale, yscale, bgValue); } else { ip.snapshot(); Undo.setup(Undo.FILTER, imp); ip.setSnapshotCopyMode(true); ip.scale(xscale, yscale); ip.setSnapshotCopyMode(false); } imp.killRoi(); imp.updateAndDraw(); imp.changes = true; } }
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(); }
void createNewStack(ImagePlus imp, ImageProcessor ip) { int nSlices = imp.getStackSize(); int w = imp.getWidth(), h = imp.getHeight(); ImagePlus imp2 = imp.createImagePlus(); Rectangle r = ip.getRoi(); boolean crop = r.width != imp.getWidth() || r.height != imp.getHeight(); ImageStack stack1 = imp.getStack(); ImageStack stack2 = new ImageStack(newWidth, newHeight); ImageProcessor ip1, ip2; int method = interpolationMethod; if (w == 1 || h == 1) method = ImageProcessor.NONE; for (int i = 1; i <= nSlices; i++) { IJ.showStatus("Scale: " + i + "/" + nSlices); ip1 = stack1.getProcessor(i); String label = stack1.getSliceLabel(i); if (crop) { ip1.setRoi(r); ip1 = ip1.crop(); } ip1.setInterpolationMethod(method); ip2 = ip1.resize(newWidth, newHeight, averageWhenDownsizing); if (ip2 != null) stack2.addSlice(label, ip2); IJ.showProgress(i, nSlices); } imp2.setStack(title, stack2); Calibration cal = imp2.getCalibration(); if (cal.scaled()) { cal.pixelWidth *= 1.0 / xscale; cal.pixelHeight *= 1.0 / yscale; } IJ.showProgress(1.0); int[] dim = imp.getDimensions(); imp2.setDimensions(dim[2], dim[3], dim[4]); if (imp.isComposite()) { imp2 = new CompositeImage(imp2, ((CompositeImage) imp).getMode()); ((CompositeImage) imp2).copyLuts(imp); } if (imp.isHyperStack()) imp2.setOpenAsHyperStack(true); if (newDepth > 0 && newDepth != oldDepth) imp2 = (new Resizer()).zScale(imp2, newDepth, interpolationMethod); if (imp2 != null) { imp2.show(); imp2.changes = true; } }
public void run(String arg) { imp = IJ.getImage(); Roi roi = imp.getRoi(); if (roi != null && !roi.isArea()) imp.killRoi(); // ignore any line selection ImageProcessor ip = imp.getProcessor(); if (!showDialog(ip)) return; if (ip.getWidth() > 1 && ip.getHeight() > 1) ip.setInterpolate(interpolate); else ip.setInterpolate(false); ip.setBackgroundValue(bgValue); imp.startTiming(); try { if (newWindow && imp.getStackSize() > 1 && processStack) createNewStack(imp, ip); else scale(ip); } catch (OutOfMemoryError o) { IJ.outOfMemory("Scale"); } IJ.showProgress(1.0); }
void createNewStack(ImagePlus imp, ImageProcessor ip) { Rectangle r = ip.getRoi(); boolean crop = r.width != imp.getWidth() || r.height != imp.getHeight(); int nSlices = imp.getStackSize(); ImageStack stack1 = imp.getStack(); ImageStack stack2 = new ImageStack(newWidth, newHeight); ImageProcessor ip1, ip2; boolean interp = interpolate; if (imp.getWidth() == 1 || imp.getHeight() == 1) interp = false; for (int i = 1; i <= nSlices; i++) { IJ.showStatus("Scale: " + i + "/" + nSlices); ip1 = stack1.getProcessor(i); String label = stack1.getSliceLabel(i); if (crop) { ip1.setRoi(r); ip1 = ip1.crop(); } ip1.setInterpolate(interp); ip2 = ip1.resize(newWidth, newHeight); if (ip2 != null) stack2.addSlice(label, ip2); IJ.showProgress(i, nSlices); } ImagePlus imp2 = imp.createImagePlus(); imp2.setStack(title, stack2); Calibration cal = imp2.getCalibration(); if (cal.scaled()) { cal.pixelWidth *= 1.0 / xscale; cal.pixelHeight *= 1.0 / yscale; } int[] dim = imp.getDimensions(); imp2.setDimensions(dim[2], dim[3], dim[4]); IJ.showProgress(1.0); if (imp.isComposite()) { imp2 = new CompositeImage(imp2, 0); ((CompositeImage) imp2).copyLuts(imp); } if (imp.isHyperStack()) imp2.setOpenAsHyperStack(true); imp2.show(); imp2.changes = true; }
String getInfo(ImagePlus imp, ImageProcessor ip) { String s = new String("\n"); s += "Title: " + imp.getTitle() + "\n"; Calibration cal = imp.getCalibration(); int stackSize = imp.getStackSize(); int channels = imp.getNChannels(); int slices = imp.getNSlices(); int frames = imp.getNFrames(); int digits = imp.getBitDepth() == 32 ? 4 : 0; if (cal.scaled()) { String unit = cal.getUnit(); String units = cal.getUnits(); s += "Width: " + IJ.d2s(imp.getWidth() * cal.pixelWidth, 2) + " " + units + " (" + imp.getWidth() + ")\n"; s += "Height: " + IJ.d2s(imp.getHeight() * cal.pixelHeight, 2) + " " + units + " (" + imp.getHeight() + ")\n"; if (slices > 1) s += "Depth: " + IJ.d2s(slices * cal.pixelDepth, 2) + " " + units + " (" + slices + ")\n"; double xResolution = 1.0 / cal.pixelWidth; double yResolution = 1.0 / cal.pixelHeight; int places = Tools.getDecimalPlaces(xResolution, yResolution); if (xResolution == yResolution) s += "Resolution: " + IJ.d2s(xResolution, places) + " pixels per " + unit + "\n"; else { s += "X Resolution: " + IJ.d2s(xResolution, places) + " pixels per " + unit + "\n"; s += "Y Resolution: " + IJ.d2s(yResolution, places) + " pixels per " + unit + "\n"; } } else { s += "Width: " + imp.getWidth() + " pixels\n"; s += "Height: " + imp.getHeight() + " pixels\n"; if (stackSize > 1) s += "Depth: " + slices + " pixels\n"; } if (stackSize > 1) s += "Voxel size: " + d2s(cal.pixelWidth) + "x" + d2s(cal.pixelHeight) + "x" + d2s(cal.pixelDepth) + " " + cal.getUnit() + "\n"; else s += "Pixel size: " + d2s(cal.pixelWidth) + "x" + d2s(cal.pixelHeight) + " " + cal.getUnit() + "\n"; s += "ID: " + imp.getID() + "\n"; String zOrigin = stackSize > 1 || cal.zOrigin != 0.0 ? "," + d2s(cal.zOrigin) : ""; s += "Coordinate origin: " + d2s(cal.xOrigin) + "," + d2s(cal.yOrigin) + zOrigin + "\n"; int type = imp.getType(); switch (type) { case ImagePlus.GRAY8: s += "Bits per pixel: 8 "; String lut = "LUT"; if (imp.getProcessor().isColorLut()) lut = "color " + lut; else lut = "grayscale " + lut; if (imp.isInvertedLut()) lut = "inverting " + lut; s += "(" + lut + ")\n"; if (imp.getNChannels() > 1) s += displayRanges(imp); else s += "Display range: " + (int) ip.getMin() + "-" + (int) ip.getMax() + "\n"; break; case ImagePlus.GRAY16: case ImagePlus.GRAY32: if (type == ImagePlus.GRAY16) { String sign = cal.isSigned16Bit() ? "signed" : "unsigned"; s += "Bits per pixel: 16 (" + sign + ")\n"; } else s += "Bits per pixel: 32 (float)\n"; if (imp.getNChannels() > 1) s += displayRanges(imp); else { s += "Display range: "; double min = ip.getMin(); double max = ip.getMax(); if (cal.calibrated()) { min = cal.getCValue((int) min); max = cal.getCValue((int) max); } s += IJ.d2s(min, digits) + " - " + IJ.d2s(max, digits) + "\n"; } break; case ImagePlus.COLOR_256: s += "Bits per pixel: 8 (color LUT)\n"; break; case ImagePlus.COLOR_RGB: s += "Bits per pixel: 32 (RGB)\n"; break; } double interval = cal.frameInterval; double fps = cal.fps; if (stackSize > 1) { ImageStack stack = imp.getStack(); int slice = imp.getCurrentSlice(); String number = slice + "/" + stackSize; String label = stack.getShortSliceLabel(slice); if (label != null && label.length() > 0) label = " (" + label + ")"; else label = ""; if (interval > 0.0 || fps != 0.0) { s += "Frame: " + number + label + "\n"; if (fps != 0.0) { String sRate = Math.abs(fps - Math.round(fps)) < 0.00001 ? IJ.d2s(fps, 0) : IJ.d2s(fps, 5); s += "Frame rate: " + sRate + " fps\n"; } if (interval != 0.0) s += "Frame interval: " + ((int) interval == interval ? IJ.d2s(interval, 0) : IJ.d2s(interval, 5)) + " " + cal.getTimeUnit() + "\n"; } else s += "Image: " + number + label + "\n"; if (imp.isHyperStack()) { if (channels > 1) s += " Channel: " + imp.getChannel() + "/" + channels + "\n"; if (slices > 1) s += " Slice: " + imp.getSlice() + "/" + slices + "\n"; if (frames > 1) s += " Frame: " + imp.getFrame() + "/" + frames + "\n"; } if (imp.isComposite()) { if (!imp.isHyperStack() && channels > 1) s += " Channels: " + channels + "\n"; String mode = ((CompositeImage) imp).getModeAsString(); s += " Composite mode: \"" + mode + "\"\n"; } } if (ip.getMinThreshold() == ImageProcessor.NO_THRESHOLD) s += "No Threshold\n"; else { double lower = ip.getMinThreshold(); double upper = ip.getMaxThreshold(); int dp = digits; if (cal.calibrated()) { lower = cal.getCValue((int) lower); upper = cal.getCValue((int) upper); dp = cal.isSigned16Bit() ? 0 : 4; } s += "Threshold: " + IJ.d2s(lower, dp) + "-" + IJ.d2s(upper, dp) + "\n"; } ImageCanvas ic = imp.getCanvas(); double mag = ic != null ? ic.getMagnification() : 1.0; if (mag != 1.0) s += "Magnification: " + IJ.d2s(mag, 2) + "\n"; if (cal.calibrated()) { s += " \n"; int curveFit = cal.getFunction(); s += "Calibration Function: "; if (curveFit == Calibration.UNCALIBRATED_OD) s += "Uncalibrated OD\n"; else if (curveFit == Calibration.CUSTOM) s += "Custom lookup table\n"; else s += CurveFitter.fList[curveFit] + "\n"; double[] c = cal.getCoefficients(); if (c != null) { s += " a: " + IJ.d2s(c[0], 6) + "\n"; s += " b: " + IJ.d2s(c[1], 6) + "\n"; if (c.length >= 3) s += " c: " + IJ.d2s(c[2], 6) + "\n"; if (c.length >= 4) s += " c: " + IJ.d2s(c[3], 6) + "\n"; if (c.length >= 5) s += " c: " + IJ.d2s(c[4], 6) + "\n"; } s += " Unit: \"" + cal.getValueUnit() + "\"\n"; } else s += "Uncalibrated\n"; FileInfo fi = imp.getOriginalFileInfo(); if (fi != null) { if (fi.url != null && !fi.url.equals("")) s += "URL: " + fi.url + "\n"; else if (fi.directory != null && fi.fileName != null) s += "Path: " + fi.directory + fi.fileName + "\n"; } ImageWindow win = imp.getWindow(); if (win != null) { Point loc = win.getLocation(); Dimension screen = IJ.getScreenSize(); s += "Screen location: " + loc.x + "," + loc.y + " (" + screen.width + "x" + screen.height + ")\n"; } Overlay overlay = imp.getOverlay(); if (overlay != null) { String hidden = imp.getHideOverlay() ? " (hidden)" : " "; int n = overlay.size(); String elements = n == 1 ? " element" : " elements"; s += "Overlay: " + n + elements + (imp.getHideOverlay() ? " (hidden)" : "") + "\n"; } else s += "No Overlay\n"; Roi roi = imp.getRoi(); if (roi == null) { if (cal.calibrated()) s += " \n"; s += "No Selection\n"; } else if (roi instanceof EllipseRoi) { s += "\nElliptical Selection\n"; double[] p = ((EllipseRoi) roi).getParams(); double dx = p[2] - p[0]; double dy = p[3] - p[1]; double major = Math.sqrt(dx * dx + dy * dy); s += " Major: " + IJ.d2s(major, 2) + "\n"; s += " Minor: " + IJ.d2s(major * p[4], 2) + "\n"; s += " X1: " + IJ.d2s(p[0], 2) + "\n"; s += " Y1: " + IJ.d2s(p[1], 2) + "\n"; s += " X2: " + IJ.d2s(p[2], 2) + "\n"; s += " Y2: " + IJ.d2s(p[3], 2) + "\n"; s += " Aspect ratio: " + IJ.d2s(p[4], 2) + "\n"; } else { s += " \n"; s += roi.getTypeAsString() + " Selection"; String points = null; if (roi instanceof PointRoi) { int npoints = ((PolygonRoi) roi).getNCoordinates(); String suffix = npoints > 1 ? "s)" : ")"; points = " (" + npoints + " point" + suffix; } String name = roi.getName(); if (name != null) { s += " (\"" + name + "\")"; if (points != null) s += "\n " + points; } else if (points != null) s += points; s += "\n"; Rectangle r = roi.getBounds(); if (roi instanceof Line) { Line line = (Line) roi; s += " X1: " + IJ.d2s(line.x1d * cal.pixelWidth) + "\n"; s += " Y1: " + IJ.d2s(yy(line.y1d, imp) * cal.pixelHeight) + "\n"; s += " X2: " + IJ.d2s(line.x2d * cal.pixelWidth) + "\n"; s += " Y2: " + IJ.d2s(yy(line.y2d, imp) * cal.pixelHeight) + "\n"; } else if (cal.scaled()) { s += " X: " + IJ.d2s(cal.getX(r.x)) + " (" + r.x + ")\n"; s += " Y: " + IJ.d2s(cal.getY(r.y, imp.getHeight())) + " (" + r.y + ")\n"; s += " Width: " + IJ.d2s(r.width * cal.pixelWidth) + " (" + r.width + ")\n"; s += " Height: " + IJ.d2s(r.height * cal.pixelHeight) + " (" + r.height + ")\n"; } else { s += " X: " + r.x + "\n"; s += " Y: " + yy(r.y, imp) + "\n"; s += " Width: " + r.width + "\n"; s += " Height: " + r.height + "\n"; } } return s; }
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(); } }
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"); }
boolean showDialog(ImageProcessor ip) { String macroOptions = Macro.getOptions(); if (macroOptions != null) { if (macroOptions.indexOf(" interpolate") != -1) macroOptions.replaceAll(" interpolate", " interpolation=Bilinear"); else if (macroOptions.indexOf(" interpolation=") == -1) macroOptions = macroOptions + " interpolation=None"; Macro.setOptions(macroOptions); } int bitDepth = imp.getBitDepth(); int stackSize = imp.getStackSize(); boolean isStack = stackSize > 1; oldDepth = stackSize; if (isStack) { xstr = "1.0"; ystr = "1.0"; zstr = "1.0"; } r = ip.getRoi(); int width = newWidth; if (width == 0) width = r.width; int height = (int) ((double) width * r.height / r.width); xscale = Tools.parseDouble(xstr, 0.0); yscale = Tools.parseDouble(ystr, 0.0); zscale = 1.0; if (xscale != 0.0 && yscale != 0.0) { width = (int) (r.width * xscale); height = (int) (r.height * yscale); } else { xstr = "-"; ystr = "-"; } GenericDialog gd = new GenericDialog("Scale"); gd.addStringField("X Scale:", xstr); gd.addStringField("Y Scale:", ystr); if (isStack) gd.addStringField("Z Scale:", zstr); gd.setInsets(5, 0, 5); gd.addStringField("Width (pixels):", "" + width); gd.addStringField("Height (pixels):", "" + height); if (isStack) { String label = "Depth (images):"; if (imp.isHyperStack()) { int slices = imp.getNSlices(); int frames = imp.getNFrames(); if (slices == 1 && frames > 1) { label = "Depth (frames):"; oldDepth = frames; } else { label = "Depth (slices):"; oldDepth = slices; } } gd.addStringField(label, "" + oldDepth); } fields = gd.getStringFields(); for (int i = 0; i < fields.size(); i++) { ((TextField) fields.elementAt(i)).addTextListener(this); ((TextField) fields.elementAt(i)).addFocusListener(this); } xField = (TextField) fields.elementAt(0); yField = (TextField) fields.elementAt(1); if (isStack) { zField = (TextField) fields.elementAt(2); widthField = (TextField) fields.elementAt(3); heightField = (TextField) fields.elementAt(4); depthField = (TextField) fields.elementAt(5); } else { widthField = (TextField) fields.elementAt(2); heightField = (TextField) fields.elementAt(3); } fieldWithFocus = xField; gd.addChoice("Interpolation:", methods, methods[interpolationMethod]); if (bitDepth == 8 || bitDepth == 24) gd.addCheckbox("Fill with background color", fillWithBackground); gd.addCheckbox("Average when downsizing", averageWhenDownsizing); boolean hyperstack = imp.isHyperStack() || imp.isComposite(); if (isStack && !hyperstack) gd.addCheckbox("Process entire stack", processStack); gd.addCheckbox("Create new window", newWindow); title = WindowManager.getUniqueName(imp.getTitle()); gd.setInsets(10, 0, 0); gd.addStringField("Title:", title, 12); gd.showDialog(); if (gd.wasCanceled()) return false; xstr = gd.getNextString(); ystr = gd.getNextString(); xscale = Tools.parseDouble(xstr, 0.0); yscale = Tools.parseDouble(ystr, 0.0); if (isStack) { zstr = gd.getNextString(); zscale = Tools.parseDouble(ystr, 0.0); } String wstr = gd.getNextString(); newWidth = (int) Tools.parseDouble(wstr, 0); newHeight = (int) Tools.parseDouble(gd.getNextString(), 0); if (newHeight != 0 && (wstr.equals("-") || wstr.equals("0"))) newWidth = (int) (newHeight * (double) r.width / r.height); if (newWidth == 0 || newHeight == 0) { IJ.error("Scaler", "Width or height is 0"); return false; } if (xscale > 0.0 && yscale > 0.0) { newWidth = (int) (r.width * xscale); newHeight = (int) (r.height * yscale); } if (isStack) newDepth = (int) Tools.parseDouble(gd.getNextString(), 0); interpolationMethod = gd.getNextChoiceIndex(); if (bitDepth == 8 || bitDepth == 24) fillWithBackground = gd.getNextBoolean(); averageWhenDownsizing = gd.getNextBoolean(); if (isStack && !hyperstack) processStack = gd.getNextBoolean(); if (hyperstack) processStack = true; newWindow = gd.getNextBoolean(); if (xscale == 0.0) { xscale = (double) newWidth / r.width; yscale = (double) newHeight / r.height; } title = gd.getNextString(); if (fillWithBackground) { Color bgc = Toolbar.getBackgroundColor(); if (bitDepth == 8) bgValue = ip.getBestIndex(bgc); else if (bitDepth == 24) bgValue = bgc.getRGB(); } else bgValue = 0.0; return true; }
/** This plugin implements the Image/Scale command. */ public class Scaler implements PlugIn, TextListener, FocusListener { private ImagePlus imp; private static String xstr = "0.5"; private static String ystr = "0.5"; private String zstr = "1.0"; private static int newWidth, newHeight; private int newDepth; private static boolean averageWhenDownsizing = true; private static boolean newWindow = true; private static int interpolationMethod = ImageProcessor.BILINEAR; private String[] methods = ImageProcessor.getInterpolationMethods(); private static boolean fillWithBackground; private static boolean processStack = true; private double xscale, yscale, zscale; private String title = "Untitled"; private Vector fields; private double bgValue; private boolean constainAspectRatio = true; private TextField xField, yField, zField, widthField, heightField, depthField; private Rectangle r; private Object fieldWithFocus; private int oldDepth; public void run(String arg) { imp = IJ.getImage(); Roi roi = imp.getRoi(); if (roi != null && !roi.isArea()) imp.deleteRoi(); // ignore any line selection ImageProcessor ip = imp.getProcessor(); if (!showDialog(ip)) return; if (newDepth > 0 && newDepth != oldDepth) { newWindow = true; processStack = true; } if ((ip.getWidth() > 1 && ip.getHeight() > 1) || newWindow) ip.setInterpolationMethod(interpolationMethod); else ip.setInterpolationMethod(ImageProcessor.NONE); ip.setBackgroundValue(bgValue); imp.startTiming(); try { if (newWindow && imp.getStackSize() > 1 && processStack) createNewStack(imp, ip); else scale(ip); } catch (OutOfMemoryError o) { IJ.outOfMemory("Scale"); } IJ.showProgress(1.0); } void createNewStack(ImagePlus imp, ImageProcessor ip) { int nSlices = imp.getStackSize(); int w = imp.getWidth(), h = imp.getHeight(); ImagePlus imp2 = imp.createImagePlus(); Rectangle r = ip.getRoi(); boolean crop = r.width != imp.getWidth() || r.height != imp.getHeight(); ImageStack stack1 = imp.getStack(); ImageStack stack2 = new ImageStack(newWidth, newHeight); ImageProcessor ip1, ip2; int method = interpolationMethod; if (w == 1 || h == 1) method = ImageProcessor.NONE; for (int i = 1; i <= nSlices; i++) { IJ.showStatus("Scale: " + i + "/" + nSlices); ip1 = stack1.getProcessor(i); String label = stack1.getSliceLabel(i); if (crop) { ip1.setRoi(r); ip1 = ip1.crop(); } ip1.setInterpolationMethod(method); ip2 = ip1.resize(newWidth, newHeight, averageWhenDownsizing); if (ip2 != null) stack2.addSlice(label, ip2); IJ.showProgress(i, nSlices); } imp2.setStack(title, stack2); Calibration cal = imp2.getCalibration(); if (cal.scaled()) { cal.pixelWidth *= 1.0 / xscale; cal.pixelHeight *= 1.0 / yscale; } IJ.showProgress(1.0); int[] dim = imp.getDimensions(); imp2.setDimensions(dim[2], dim[3], dim[4]); if (imp.isComposite()) { imp2 = new CompositeImage(imp2, ((CompositeImage) imp).getMode()); ((CompositeImage) imp2).copyLuts(imp); } if (imp.isHyperStack()) imp2.setOpenAsHyperStack(true); if (newDepth > 0 && newDepth != oldDepth) imp2 = (new Resizer()).zScale(imp2, newDepth, interpolationMethod); if (imp2 != null) { imp2.show(); imp2.changes = true; } } void scale(ImageProcessor ip) { if (newWindow) { Rectangle r = ip.getRoi(); ImagePlus imp2 = imp.createImagePlus(); imp2.setProcessor(title, ip.resize(newWidth, newHeight, averageWhenDownsizing)); Calibration cal = imp2.getCalibration(); if (cal.scaled()) { cal.pixelWidth *= 1.0 / xscale; cal.pixelHeight *= 1.0 / yscale; } imp2.show(); imp.trimProcessor(); imp2.trimProcessor(); imp2.changes = true; } else { if (processStack && imp.getStackSize() > 1) { Undo.reset(); StackProcessor sp = new StackProcessor(imp.getStack(), ip); sp.scale(xscale, yscale, bgValue); } else { ip.snapshot(); Undo.setup(Undo.FILTER, imp); ip.setSnapshotCopyMode(true); ip.scale(xscale, yscale); ip.setSnapshotCopyMode(false); } imp.deleteRoi(); imp.updateAndDraw(); imp.changes = true; } } boolean showDialog(ImageProcessor ip) { String macroOptions = Macro.getOptions(); if (macroOptions != null) { if (macroOptions.indexOf(" interpolate") != -1) macroOptions.replaceAll(" interpolate", " interpolation=Bilinear"); else if (macroOptions.indexOf(" interpolation=") == -1) macroOptions = macroOptions + " interpolation=None"; Macro.setOptions(macroOptions); } int bitDepth = imp.getBitDepth(); int stackSize = imp.getStackSize(); boolean isStack = stackSize > 1; oldDepth = stackSize; if (isStack) { xstr = "1.0"; ystr = "1.0"; zstr = "1.0"; } r = ip.getRoi(); int width = newWidth; if (width == 0) width = r.width; int height = (int) ((double) width * r.height / r.width); xscale = Tools.parseDouble(xstr, 0.0); yscale = Tools.parseDouble(ystr, 0.0); zscale = 1.0; if (xscale != 0.0 && yscale != 0.0) { width = (int) (r.width * xscale); height = (int) (r.height * yscale); } else { xstr = "-"; ystr = "-"; } GenericDialog gd = new GenericDialog("Scale"); gd.addStringField("X Scale:", xstr); gd.addStringField("Y Scale:", ystr); if (isStack) gd.addStringField("Z Scale:", zstr); gd.setInsets(5, 0, 5); gd.addStringField("Width (pixels):", "" + width); gd.addStringField("Height (pixels):", "" + height); if (isStack) { String label = "Depth (images):"; if (imp.isHyperStack()) { int slices = imp.getNSlices(); int frames = imp.getNFrames(); if (slices == 1 && frames > 1) { label = "Depth (frames):"; oldDepth = frames; } else { label = "Depth (slices):"; oldDepth = slices; } } gd.addStringField(label, "" + oldDepth); } fields = gd.getStringFields(); for (int i = 0; i < fields.size(); i++) { ((TextField) fields.elementAt(i)).addTextListener(this); ((TextField) fields.elementAt(i)).addFocusListener(this); } xField = (TextField) fields.elementAt(0); yField = (TextField) fields.elementAt(1); if (isStack) { zField = (TextField) fields.elementAt(2); widthField = (TextField) fields.elementAt(3); heightField = (TextField) fields.elementAt(4); depthField = (TextField) fields.elementAt(5); } else { widthField = (TextField) fields.elementAt(2); heightField = (TextField) fields.elementAt(3); } fieldWithFocus = xField; gd.addChoice("Interpolation:", methods, methods[interpolationMethod]); if (bitDepth == 8 || bitDepth == 24) gd.addCheckbox("Fill with background color", fillWithBackground); gd.addCheckbox("Average when downsizing", averageWhenDownsizing); boolean hyperstack = imp.isHyperStack() || imp.isComposite(); if (isStack && !hyperstack) gd.addCheckbox("Process entire stack", processStack); gd.addCheckbox("Create new window", newWindow); title = WindowManager.getUniqueName(imp.getTitle()); gd.setInsets(10, 0, 0); gd.addStringField("Title:", title, 12); gd.showDialog(); if (gd.wasCanceled()) return false; xstr = gd.getNextString(); ystr = gd.getNextString(); xscale = Tools.parseDouble(xstr, 0.0); yscale = Tools.parseDouble(ystr, 0.0); if (isStack) { zstr = gd.getNextString(); zscale = Tools.parseDouble(ystr, 0.0); } String wstr = gd.getNextString(); newWidth = (int) Tools.parseDouble(wstr, 0); newHeight = (int) Tools.parseDouble(gd.getNextString(), 0); if (newHeight != 0 && (wstr.equals("-") || wstr.equals("0"))) newWidth = (int) (newHeight * (double) r.width / r.height); if (newWidth == 0 || newHeight == 0) { IJ.error("Scaler", "Width or height is 0"); return false; } if (xscale > 0.0 && yscale > 0.0) { newWidth = (int) (r.width * xscale); newHeight = (int) (r.height * yscale); } if (isStack) newDepth = (int) Tools.parseDouble(gd.getNextString(), 0); interpolationMethod = gd.getNextChoiceIndex(); if (bitDepth == 8 || bitDepth == 24) fillWithBackground = gd.getNextBoolean(); averageWhenDownsizing = gd.getNextBoolean(); if (isStack && !hyperstack) processStack = gd.getNextBoolean(); if (hyperstack) processStack = true; newWindow = gd.getNextBoolean(); if (xscale == 0.0) { xscale = (double) newWidth / r.width; yscale = (double) newHeight / r.height; } title = gd.getNextString(); if (fillWithBackground) { Color bgc = Toolbar.getBackgroundColor(); if (bitDepth == 8) bgValue = ip.getBestIndex(bgc); else if (bitDepth == 24) bgValue = bgc.getRGB(); } else bgValue = 0.0; return true; } public void textValueChanged(TextEvent e) { Object source = e.getSource(); double newXScale = xscale; double newYScale = yscale; double newZScale = zscale; if (source == xField && fieldWithFocus == xField) { String newXText = xField.getText(); newXScale = Tools.parseDouble(newXText, 0); if (newXScale == 0) return; if (newXScale != xscale) { int newWidth = (int) (newXScale * r.width); widthField.setText("" + newWidth); if (constainAspectRatio) { yField.setText(newXText); int newHeight = (int) (newXScale * r.height); heightField.setText("" + newHeight); } } } else if (source == yField && fieldWithFocus == yField) { String newYText = yField.getText(); newYScale = Tools.parseDouble(newYText, 0); if (newYScale == 0) return; if (newYScale != yscale) { int newHeight = (int) (newYScale * r.height); heightField.setText("" + newHeight); } } else if (source == zField && fieldWithFocus == zField) { String newZText = zField.getText(); newZScale = Tools.parseDouble(newZText, 0); if (newZScale == 0) return; if (newZScale != zscale) { int nSlices = imp.getStackSize(); if (imp.isHyperStack()) { int slices = imp.getNSlices(); int frames = imp.getNFrames(); if (slices == 1 && frames > 1) nSlices = frames; else nSlices = slices; } int newDepth = (int) (newZScale * nSlices); depthField.setText("" + newDepth); } } else if (source == widthField && fieldWithFocus == widthField) { int newWidth = (int) Tools.parseDouble(widthField.getText(), 0.0); if (newWidth != 0) { int newHeight = (int) (newWidth * (double) r.height / r.width); heightField.setText("" + newHeight); xField.setText("-"); yField.setText("-"); newXScale = 0.0; newYScale = 0.0; } } else if (source == depthField && fieldWithFocus == depthField) { int newDepth = (int) Tools.parseDouble(depthField.getText(), 0.0); if (newDepth != 0) { zField.setText("-"); newZScale = 0.0; } } xscale = newXScale; yscale = newYScale; zscale = newZScale; } public void focusGained(FocusEvent e) { fieldWithFocus = e.getSource(); if (fieldWithFocus == widthField) constainAspectRatio = true; else if (fieldWithFocus == yField) constainAspectRatio = false; } public void focusLost(FocusEvent e) {} }
void apply(ImagePlus imp, ImageProcessor ip) { // this.setCursor(wait); // IJ.showStatus("Bandpassing slice "+previousSlice); java.awt.Color col; if (invert.getState()) col = Toolbar.getForegroundColor(); else col = Toolbar.getBackgroundColor(); ip.setColor(col); int fill = ip.BLACK; int keep = 0; if (bandPassH.getState() && bandPassS.getState() && bandPassB.getState()) { // PPP All pass for (int j = 0; j < numPixels; j++) { int hue = hSource[j] & 0xff; int sat = sSource[j] & 0xff; int bri = bSource[j] & 0xff; if (((hue < minHue) || (hue > maxHue)) || ((sat < minSat) || (sat > maxSat)) || ((bri < minBri) || (bri > maxBri))) fillMask[j] = fill; else fillMask[j] = keep; } } else if (!bandPassH.getState() && !bandPassS.getState() && !bandPassB.getState()) { // SSS All stop for (int j = 0; j < numPixels; j++) { int hue = hSource[j] & 0xff; int sat = sSource[j] & 0xff; int bri = bSource[j] & 0xff; if (((hue >= minHue) && (hue <= maxHue)) || ((sat >= minSat) && (sat <= maxSat)) || ((bri >= minBri) && (bri <= maxBri))) fillMask[j] = fill; else fillMask[j] = keep; } } else if (bandPassH.getState() && bandPassS.getState() && !bandPassB.getState()) { // PPS for (int j = 0; j < numPixels; j++) { int hue = hSource[j] & 0xff; int sat = sSource[j] & 0xff; int bri = bSource[j] & 0xff; if (((hue < minHue) || (hue > maxHue)) || ((sat < minSat) || (sat > maxSat)) || ((bri >= minBri) && (bri <= maxBri))) fillMask[j] = fill; else fillMask[j] = keep; } } else if (!bandPassH.getState() && !bandPassS.getState() && bandPassB.getState()) { // SSP for (int j = 0; j < numPixels; j++) { int hue = hSource[j] & 0xff; int sat = sSource[j] & 0xff; int bri = bSource[j] & 0xff; if (((hue >= minHue) && (hue <= maxHue)) || ((sat >= minSat) && (sat <= maxSat)) || ((bri < minBri) || (bri > maxBri))) fillMask[j] = fill; else fillMask[j] = keep; } } else if (bandPassH.getState() && !bandPassS.getState() && !bandPassB.getState()) { // PSS for (int j = 0; j < numPixels; j++) { int hue = hSource[j] & 0xff; int sat = sSource[j] & 0xff; int bri = bSource[j] & 0xff; if (((hue < minHue) || (hue > maxHue)) || ((sat >= minSat) && (sat <= maxSat)) || ((bri >= minBri) && (bri <= maxBri))) fillMask[j] = fill; else fillMask[j] = keep; } } else if (!bandPassH.getState() && bandPassS.getState() && bandPassB.getState()) { // SPP for (int j = 0; j < numPixels; j++) { int hue = hSource[j] & 0xff; int sat = sSource[j] & 0xff; int bri = bSource[j] & 0xff; if (((hue >= minHue) && (hue <= maxHue)) || ((sat < minSat) || (sat > maxSat)) || ((bri < minBri) || (bri > maxBri))) fillMask[j] = fill; else fillMask[j] = keep; } } else if (!bandPassH.getState() && bandPassS.getState() && !bandPassB.getState()) { // SPS for (int j = 0; j < numPixels; j++) { int hue = hSource[j] & 0xff; int sat = sSource[j] & 0xff; int bri = bSource[j] & 0xff; if (((hue >= minHue) && (hue <= maxHue)) || ((sat < minSat) || (sat > maxSat)) || ((bri >= minBri) && (bri <= maxBri))) fillMask[j] = fill; else fillMask[j] = keep; } } else if (bandPassH.getState() && !bandPassS.getState() && bandPassB.getState()) { // PSP for (int j = 0; j < numPixels; j++) { int hue = hSource[j] & 0xff; int sat = sSource[j] & 0xff; int bri = bSource[j] & 0xff; if (((hue < minHue) || (hue > maxHue)) || ((sat >= minSat) && (sat <= maxSat)) || ((bri < minBri) || (bri > maxBri))) fillMask[j] = fill; else fillMask[j] = keep; } } ip.fill(fillMask); if (threshold.getState()) { ip.invert(); for (int j = 0; j < numPixels; j++) { if (fillMask[j] == fill) fillMask[j] = keep; else fillMask[j] = fill; } ip.fill(fillMask); ip.invert(); } }
ImageProcessor setup(ImagePlus imp) { ImageProcessor ip; int type = imp.getType(); if (type != ImagePlus.COLOR_RGB) return null; ip = imp.getProcessor(); int id = imp.getID(); int slice = imp.getCurrentSlice(); if ((id != previousImageID) | (slice != previousSlice) | (flag)) { flag = false; // if true, flags a change from HSB to RGB or viceversa numSlices = imp.getStackSize(); stack = imp.getStack(); width = stack.getWidth(); height = stack.getHeight(); numPixels = width * height; hSource = new byte[numPixels]; sSource = new byte[numPixels]; bSource = new byte[numPixels]; // restore = (int[])ip.getPixelsCopy(); //This runs into trouble sometimes, so do it the // long way: int[] temp = (int[]) ip.getPixels(); restore = new int[numPixels]; for (int i = 0; i < numPixels; i++) restore[i] = temp[i]; fillMask = new int[numPixels]; // Get hsb or rgb from image. ColorProcessor cp = (ColorProcessor) ip; IJ.showStatus("Gathering data"); if (isRGB) cp.getRGB(hSource, sSource, bSource); else cp.getHSB(hSource, sSource, bSource); IJ.showStatus("done"); // Create a spectrum ColorModel for the Hue histogram plot. Color c; byte[] reds = new byte[256]; byte[] greens = new byte[256]; byte[] blues = new byte[256]; for (int i = 0; i < 256; i++) { c = Color.getHSBColor(i / 255f, 1f, 1f); reds[i] = (byte) c.getRed(); greens[i] = (byte) c.getGreen(); blues[i] = (byte) c.getBlue(); } ColorModel cm = new IndexColorModel(8, 256, reds, greens, blues); // Make an image with just the hue from the RGB image and the spectrum LUT. // This is just for a hue histogram for the plot. Do not show it. // ByteProcessor bpHue = new ByteProcessor(width,height,h,cm); ByteProcessor bpHue = new ByteProcessor(width, height, hSource, cm); ImagePlus impHue = new ImagePlus("Hue", bpHue); // impHue.show(); ByteProcessor bpSat = new ByteProcessor(width, height, sSource, cm); ImagePlus impSat = new ImagePlus("Sat", bpSat); // impSat.show(); ByteProcessor bpBri = new ByteProcessor(width, height, bSource, cm); ImagePlus impBri = new ImagePlus("Bri", bpBri); // impBri.show(); plot.setHistogram(impHue, 0); splot.setHistogram(impSat, 1); bplot.setHistogram(impBri, 2); updateLabels(); updatePlot(); updateScrollBars(); imp.updateAndDraw(); } previousImageID = id; previousSlice = slice; return ip; }
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); } } }
boolean showDialog(ImageProcessor ip) { int bitDepth = imp.getBitDepth(); boolean isStack = imp.getStackSize() > 1; r = ip.getRoi(); int width = newWidth; if (width == 0) width = r.width; int height = (int) ((double) width * r.height / r.width); xscale = Tools.parseDouble(xstr, 0.0); yscale = Tools.parseDouble(ystr, 0.0); if (xscale != 0.0 && yscale != 0.0) { width = (int) (r.width * xscale); height = (int) (r.height * yscale); } else { xstr = "-"; ystr = "-"; } GenericDialog gd = new GenericDialog("Scale"); gd.addStringField("X Scale (0.05-25):", xstr); gd.addStringField("Y Scale (0.05-25):", ystr); gd.setInsets(5, 0, 5); gd.addStringField("Width (pixels):", "" + width); gd.addStringField("Height (pixels):", "" + height); fields = gd.getStringFields(); for (int i = 0; i < 3; i++) { ((TextField) fields.elementAt(i)).addTextListener(this); ((TextField) fields.elementAt(i)).addFocusListener(this); } xField = (TextField) fields.elementAt(0); yField = (TextField) fields.elementAt(1); widthField = (TextField) fields.elementAt(2); heightField = (TextField) fields.elementAt(3); fieldWithFocus = xField; gd.addCheckbox("Interpolate", interpolate); if (bitDepth == 8 || bitDepth == 24) gd.addCheckbox("Fill with Background Color", fillWithBackground); if (isStack) gd.addCheckbox("Process Entire Stack", processStack); gd.addCheckbox("Create New Window", newWindow); title = WindowManager.getUniqueName(imp.getTitle()); gd.setInsets(10, 0, 0); gd.addStringField("Title:", title, 12); gd.showDialog(); if (gd.wasCanceled()) return false; xstr = gd.getNextString(); ystr = gd.getNextString(); xscale = Tools.parseDouble(xstr, 0.0); yscale = Tools.parseDouble(ystr, 0.0); String wstr = gd.getNextString(); newWidth = (int) Tools.parseDouble(wstr, 0); newHeight = (int) Tools.parseDouble(gd.getNextString(), 0); if (newHeight != 0 && (wstr.equals("-") || wstr.equals("0"))) newWidth = (int) (newHeight * (double) r.width / r.height); if (newWidth == 0 || newHeight == 0) { IJ.error("Invalid width or height entered"); return false; } if (xscale > 25.0) xscale = 25.0; if (yscale > 25.0) yscale = 25.0; if (xscale > 0.0 && yscale > 0.0) { newWidth = (int) (r.width * xscale); newHeight = (int) (r.height * yscale); } interpolate = gd.getNextBoolean(); if (bitDepth == 8 || bitDepth == 24) fillWithBackground = gd.getNextBoolean(); if (isStack) processStack = gd.getNextBoolean(); newWindow = gd.getNextBoolean(); if (!newWindow && xscale == 0.0) { xscale = (double) newWidth / r.width; yscale = (double) newHeight / r.height; } title = gd.getNextString(); if (fillWithBackground) { Color bgc = Toolbar.getBackgroundColor(); if (bitDepth == 8) bgValue = ip.getBestIndex(bgc); else if (bitDepth == 24) bgValue = bgc.getRGB(); } else { if (bitDepth == 8) bgValue = ip.isInvertedLut() ? 0.0 : 255.0; // white else if (bitDepth == 24) bgValue = 0xffffffff; // white } return true; }