Exemplo n.º 1
0
 void configureProxy() {
   if (Prefs.useSystemProxies) {
     try {
       System.setProperty("java.net.useSystemProxies", "true");
     } catch (Exception e) {
     }
   } else {
     String server = Prefs.get("proxy.server", null);
     if (server == null || server.equals("")) return;
     int port = (int) Prefs.get("proxy.port", 0);
     if (port == 0) return;
     Properties props = System.getProperties();
     props.put("proxySet", "true");
     props.put("http.proxyHost", server);
     props.put("http.proxyPort", "" + port);
   }
   // new ProxySettings().logProperties();
 }
Exemplo n.º 2
0
  // Input/Output options
  void io() {
    GenericDialog gd = new GenericDialog("I/O Options");
    gd.addNumericField("JPEG quality (0-100):", FileSaver.getJpegQuality(), 0, 3, "");
    gd.addNumericField("GIF and PNG transparent index:", Prefs.getTransparentIndex(), 0, 3, "");
    gd.addStringField(
        "File extension for tables (.txt, .xls or .csv):", Prefs.get("options.ext", ".csv"), 4);
    gd.addCheckbox("Use JFileChooser to open/save", Prefs.useJFileChooser);
    if (!IJ.isMacOSX())
      gd.addCheckbox("Use_file chooser to import sequences", Prefs.useFileChooser);
    gd.addCheckbox("Save TIFF and raw in Intel byte order", Prefs.intelByteOrder);
    gd.addCheckbox("Skip dialog when opening .raw files", Prefs.skipRawDialog);

    gd.setInsets(15, 20, 0);
    gd.addMessage("Results Table Options");
    gd.setInsets(3, 40, 0);
    gd.addCheckbox("Copy_column headers", Prefs.copyColumnHeaders);
    gd.setInsets(0, 40, 0);
    gd.addCheckbox("Copy_row numbers", !Prefs.noRowNumbers);
    gd.setInsets(0, 40, 0);
    gd.addCheckbox("Save_column headers", !Prefs.dontSaveHeaders);
    gd.setInsets(0, 40, 0);
    gd.addCheckbox("Save_row numbers", !Prefs.dontSaveRowNumbers);

    gd.showDialog();
    if (gd.wasCanceled()) return;
    int quality = (int) gd.getNextNumber();
    if (quality < 0) quality = 0;
    if (quality > 100) quality = 100;
    FileSaver.setJpegQuality(quality);
    int transparentIndex = (int) gd.getNextNumber();
    Prefs.setTransparentIndex(transparentIndex);
    String extension = gd.getNextString();
    if (!extension.startsWith(".")) extension = "." + extension;
    Prefs.set("options.ext", extension);
    Prefs.useJFileChooser = gd.getNextBoolean();
    if (!IJ.isMacOSX()) Prefs.useFileChooser = gd.getNextBoolean();
    Prefs.intelByteOrder = gd.getNextBoolean();
    Prefs.skipRawDialog = gd.getNextBoolean();
    Prefs.copyColumnHeaders = gd.getNextBoolean();
    Prefs.noRowNumbers = !gd.getNextBoolean();
    Prefs.dontSaveHeaders = !gd.getNextBoolean();
    Prefs.dontSaveRowNumbers = !gd.getNextBoolean();
    return;
  }
Exemplo n.º 3
0
public class vvd_easy_export implements PlugIn {
  String basename;
  String directory;
  ArrayList<String> lvImgTitle;
  int bw = 128, bh = 128, bd = 64, lv = 1;
  String filetype = (String) Prefs.get("filetype.string", "RAW");
  int jpeg_quality = (int) Prefs.get("jpeg_quality.int", FileSaver.DEFAULT_JPEG_QUALITY);
  int bdsizelimit = (int) Prefs.get("bdsizelimit.int", 50);
  ArrayList<Integer> bwlist = new ArrayList<Integer>();
  ArrayList<Integer> bhlist = new ArrayList<Integer>();
  ArrayList<Integer> bdlist = new ArrayList<Integer>();

  class Brick {
    public int x_, y_, z_;
    public int w_, h_, d_;
    public long offset_, size_;
    public double tx0_, ty0_, tz0_, tx1_, ty1_, tz1_;
    public double bx0_, by0_, bz0_, bx1_, by1_, bz1_;

    Brick(
        int x,
        int y,
        int z,
        int w,
        int h,
        int d,
        long offset,
        long size,
        double tx0,
        double ty0,
        double tz0,
        double tx1,
        double ty1,
        double tz1,
        double bx0,
        double by0,
        double bz0,
        double bx1,
        double by1,
        double bz1) {
      x_ = x;
      y_ = y;
      z_ = z;
      w_ = w;
      h_ = h;
      d_ = d;
      offset_ = offset;
      size_ = size;
      tx0_ = tx0;
      ty0_ = ty0;
      tz0_ = tz0;
      tx1_ = tx1;
      ty1_ = ty1;
      tz1_ = tz1;
      bx0_ = bx0;
      by0_ = by0;
      bz0_ = bz0;
      bx1_ = bx1;
      by1_ = by1;
      bz1_ = bz1;
    }
  }

  public void run(String arg) {
    if (IJ.versionLessThan("1.49d")) return;

    if (!showDialog()) return;

    SaveDialog sd = new SaveDialog("Save as Bricks...", "", "");
    basename = sd.getFileName();
    directory = sd.getDirectory();
    if (basename == null || directory == null) return;

    build_bricks();
  }

  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;
  }

  public static int log2(int n) {
    if (n <= 0) return 0;
    return 31 - Integer.numberOfLeadingZeros(n);
  }

  public void build_bricks() {

    ImagePlus imp;
    ImagePlus orgimp;
    ImageStack stack;
    FileInfo finfo;

    if (lvImgTitle.isEmpty()) return;
    orgimp = WindowManager.getImage(lvImgTitle.get(0));
    imp = orgimp;

    finfo = imp.getFileInfo();
    if (finfo == null) return;

    int[] dims = imp.getDimensions();
    int imageW = dims[0];
    int imageH = dims[1];
    int nCh = dims[2];
    int imageD = dims[3];
    int nFrame = dims[4];
    int bdepth = imp.getBitDepth();
    double xspc = finfo.pixelWidth;
    double yspc = finfo.pixelHeight;
    double zspc = finfo.pixelDepth;
    double z_aspect = Math.max(xspc, yspc) / zspc;

    int orgW = imageW;
    int orgH = imageH;
    int orgD = imageD;
    double orgxspc = xspc;
    double orgyspc = yspc;
    double orgzspc = zspc;

    lv = lvImgTitle.size();
    if (filetype == "JPEG") {
      for (int l = 0; l < lv; l++) {
        if (WindowManager.getImage(lvImgTitle.get(l)).getBitDepth() != 8) {
          IJ.error("A SOURCE IMAGE MUST BE 8BIT GLAYSCALE");
          return;
        }
      }
    }

    // calculate levels
    /*		int baseXY = 256;
    		int baseZ = 256;

    		if (z_aspect < 0.5) baseZ = 128;
    		if (z_aspect > 2.0) baseXY = 128;
    		if (z_aspect >= 0.5 && z_aspect < 1.0) baseZ = (int)(baseZ*z_aspect);
    		if (z_aspect > 1.0 && z_aspect <= 2.0) baseXY = (int)(baseXY/z_aspect);

    		IJ.log("Z_aspect: " + z_aspect);
    		IJ.log("BaseXY: " + baseXY);
    		IJ.log("BaseZ: " + baseZ);
    */

    int baseXY = 256;
    int baseZ = 128;
    int dbXY = Math.max(orgW, orgH) / baseXY;
    if (Math.max(orgW, orgH) % baseXY > 0) dbXY *= 2;
    int dbZ = orgD / baseZ;
    if (orgD % baseZ > 0) dbZ *= 2;
    lv = Math.max(log2(dbXY), log2(dbZ)) + 1;

    int ww = orgW;
    int hh = orgH;
    int dd = orgD;
    for (int l = 0; l < lv; l++) {
      int bwnum = ww / baseXY;
      if (ww % baseXY > 0) bwnum++;
      int bhnum = hh / baseXY;
      if (hh % baseXY > 0) bhnum++;
      int bdnum = dd / baseZ;
      if (dd % baseZ > 0) bdnum++;

      if (bwnum % 2 == 0) bwnum++;
      if (bhnum % 2 == 0) bhnum++;
      if (bdnum % 2 == 0) bdnum++;

      int bw = (bwnum <= 1) ? ww : ww / bwnum + 1 + (ww % bwnum > 0 ? 1 : 0);
      int bh = (bhnum <= 1) ? hh : hh / bhnum + 1 + (hh % bhnum > 0 ? 1 : 0);
      int bd = (bdnum <= 1) ? dd : dd / bdnum + 1 + (dd % bdnum > 0 ? 1 : 0);

      bwlist.add(bw);
      bhlist.add(bh);
      bdlist.add(bd);

      IJ.log("LEVEL: " + l);
      IJ.log("  width: " + ww);
      IJ.log("  hight: " + hh);
      IJ.log("  depth: " + dd);
      IJ.log("  bw: " + bw);
      IJ.log("  bh: " + bh);
      IJ.log("  bd: " + bd);

      int xyl2 = Math.max(ww, hh) / baseXY;
      if (Math.max(ww, hh) % baseXY > 0) xyl2 *= 2;
      if (lv - 1 - log2(xyl2) <= l) {
        ww /= 2;
        hh /= 2;
      }
      IJ.log("  xyl2: " + (lv - 1 - log2(xyl2)));

      int zl2 = dd / baseZ;
      if (dd % baseZ > 0) zl2 *= 2;
      if (lv - 1 - log2(zl2) <= l) dd /= 2;
      IJ.log("  zl2: " + (lv - 1 - log2(zl2)));

      if (l < lv - 1) {
        lvImgTitle.add(lvImgTitle.get(0) + "_level" + (l + 1));
        IJ.selectWindow(lvImgTitle.get(0));
        IJ.run(
            "Scale...",
            "x=- y=- z=- width="
                + ww
                + " height="
                + hh
                + " depth="
                + dd
                + " interpolation=Bicubic average process create title="
                + lvImgTitle.get(l + 1));
      }
    }

    for (int l = 0; l < lv; l++) {
      IJ.log(lvImgTitle.get(l));
    }

    Document doc = newXMLDocument();
    Element root = doc.createElement("BRK");
    root.setAttribute("version", "1.0");
    root.setAttribute("nLevel", String.valueOf(lv));
    root.setAttribute("nChannel", String.valueOf(nCh));
    root.setAttribute("nFrame", String.valueOf(nFrame));
    doc.appendChild(root);

    for (int l = 0; l < lv; l++) {
      IJ.showProgress(0.0);

      int[] dims2 = imp.getDimensions();
      IJ.log(
          "W: "
              + String.valueOf(dims2[0])
              + " H: "
              + String.valueOf(dims2[1])
              + " C: "
              + String.valueOf(dims2[2])
              + " D: "
              + String.valueOf(dims2[3])
              + " T: "
              + String.valueOf(dims2[4])
              + " b: "
              + String.valueOf(bdepth));

      bw = bwlist.get(l).intValue();
      bh = bhlist.get(l).intValue();
      bd = bdlist.get(l).intValue();

      boolean force_pow2 = false;
      /*			if(IsPowerOf2(bw) && IsPowerOf2(bh) && IsPowerOf2(bd)) force_pow2 = true;

      			if(force_pow2){
      				//force pow2
      				if(Pow2(bw) > bw) bw = Pow2(bw)/2;
      				if(Pow2(bh) > bh) bh = Pow2(bh)/2;
      				if(Pow2(bd) > bd) bd = Pow2(bd)/2;
      			}

      			if(bw > imageW) bw = (Pow2(imageW) == imageW) ? imageW : Pow2(imageW)/2;
      			if(bh > imageH) bh = (Pow2(imageH) == imageH) ? imageH : Pow2(imageH)/2;
      			if(bd > imageD) bd = (Pow2(imageD) == imageD) ? imageD : Pow2(imageD)/2;

      */
      if (bw > imageW) bw = imageW;
      if (bh > imageH) bh = imageH;
      if (bd > imageD) bd = imageD;

      if (bw <= 1 || bh <= 1 || bd <= 1) break;

      if (filetype == "JPEG" && (bw < 8 || bh < 8)) break;

      Element lvnode = doc.createElement("Level");
      lvnode.setAttribute("lv", String.valueOf(l));
      lvnode.setAttribute("imageW", String.valueOf(imageW));
      lvnode.setAttribute("imageH", String.valueOf(imageH));
      lvnode.setAttribute("imageD", String.valueOf(imageD));
      lvnode.setAttribute("xspc", String.valueOf(xspc));
      lvnode.setAttribute("yspc", String.valueOf(yspc));
      lvnode.setAttribute("zspc", String.valueOf(zspc));
      lvnode.setAttribute("bitDepth", String.valueOf(bdepth));
      root.appendChild(lvnode);

      Element brksnode = doc.createElement("Bricks");
      brksnode.setAttribute("brick_baseW", String.valueOf(bw));
      brksnode.setAttribute("brick_baseH", String.valueOf(bh));
      brksnode.setAttribute("brick_baseD", String.valueOf(bd));
      lvnode.appendChild(brksnode);

      ArrayList<Brick> bricks = new ArrayList<Brick>();
      int mw, mh, md, mw2, mh2, md2;
      double tx0, ty0, tz0, tx1, ty1, tz1;
      double bx0, by0, bz0, bx1, by1, bz1;
      for (int k = 0; k < imageD; k += bd) {
        if (k > 0) k--;
        for (int j = 0; j < imageH; j += bh) {
          if (j > 0) j--;
          for (int i = 0; i < imageW; i += bw) {
            if (i > 0) i--;
            mw = Math.min(bw, imageW - i);
            mh = Math.min(bh, imageH - j);
            md = Math.min(bd, imageD - k);

            if (force_pow2) {
              mw2 = Pow2(mw);
              mh2 = Pow2(mh);
              md2 = Pow2(md);
            } else {
              mw2 = mw;
              mh2 = mh;
              md2 = md;
            }

            if (filetype == "JPEG") {
              if (mw2 < 8) mw2 = 8;
              if (mh2 < 8) mh2 = 8;
            }

            tx0 = i == 0 ? 0.0d : ((mw2 - mw + 0.5d) / mw2);
            ty0 = j == 0 ? 0.0d : ((mh2 - mh + 0.5d) / mh2);
            tz0 = k == 0 ? 0.0d : ((md2 - md + 0.5d) / md2);

            tx1 = 1.0d - 0.5d / mw2;
            if (mw < bw) tx1 = 1.0d;
            if (imageW - i == bw) tx1 = 1.0d;

            ty1 = 1.0d - 0.5d / mh2;
            if (mh < bh) ty1 = 1.0d;
            if (imageH - j == bh) ty1 = 1.0d;

            tz1 = 1.0d - 0.5d / md2;
            if (md < bd) tz1 = 1.0d;
            if (imageD - k == bd) tz1 = 1.0d;

            bx0 = i == 0 ? 0.0d : (i + 0.5d) / (double) imageW;
            by0 = j == 0 ? 0.0d : (j + 0.5d) / (double) imageH;
            bz0 = k == 0 ? 0.0d : (k + 0.5d) / (double) imageD;

            bx1 = Math.min((i + bw - 0.5d) / (double) imageW, 1.0d);
            if (imageW - i == bw) bx1 = 1.0d;

            by1 = Math.min((j + bh - 0.5d) / (double) imageH, 1.0d);
            if (imageH - j == bh) by1 = 1.0d;

            bz1 = Math.min((k + bd - 0.5d) / (double) imageD, 1.0d);
            if (imageD - k == bd) bz1 = 1.0d;

            int x, y, z;
            x = i - (mw2 - mw);
            y = j - (mh2 - mh);
            z = k - (md2 - md);
            bricks.add(
                new Brick(
                    x, y, z, mw2, mh2, md2, 0, 0, tx0, ty0, tz0, tx1, ty1, tz1, bx0, by0, bz0, bx1,
                    by1, bz1));
          }
        }
      }

      Element fsnode = doc.createElement("Files");
      lvnode.appendChild(fsnode);

      stack = imp.getStack();

      int totalbricknum = nFrame * nCh * bricks.size();
      int curbricknum = 0;
      for (int f = 0; f < nFrame; f++) {
        for (int ch = 0; ch < nCh; ch++) {
          int sizelimit = bdsizelimit * 1024 * 1024;
          int bytecount = 0;
          int filecount = 0;
          int pd_bufsize = Math.max(sizelimit, bw * bh * bd * bdepth / 8);
          byte[] packed_data = new byte[pd_bufsize];
          String base_dataname =
              basename
                  + "_Lv"
                  + String.valueOf(l)
                  + "_Ch"
                  + String.valueOf(ch)
                  + "_Fr"
                  + String.valueOf(f);
          String current_dataname = base_dataname + "_data" + filecount;

          Brick b_first = bricks.get(0);
          if (b_first.z_ != 0) IJ.log("warning");
          int st_z = b_first.z_;
          int ed_z = b_first.z_ + b_first.d_;
          LinkedList<ImageProcessor> iplist = new LinkedList<ImageProcessor>();
          for (int s = st_z; s < ed_z; s++)
            iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));

          //					ImagePlus test;
          //					ImageStack tsst;
          //					test = NewImage.createByteImage("test", imageW, imageH, imageD,
          // NewImage.FILL_BLACK);
          //					tsst = test.getStack();
          for (int i = 0; i < bricks.size(); i++) {
            Brick b = bricks.get(i);

            if (ed_z > b.z_ || st_z < b.z_ + b.d_) {
              if (b.z_ > st_z) {
                for (int s = 0; s < b.z_ - st_z; s++) iplist.pollFirst();
                st_z = b.z_;
              } else if (b.z_ < st_z) {
                IJ.log("warning");
                for (int s = st_z - 1; s > b.z_; s--)
                  iplist.addFirst(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                st_z = b.z_;
              }

              if (b.z_ + b.d_ > ed_z) {
                for (int s = ed_z; s < b.z_ + b.d_; s++)
                  iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                ed_z = b.z_ + b.d_;
              } else if (b.z_ + b.d_ < ed_z) {
                IJ.log("warning");
                for (int s = 0; s < ed_z - (b.z_ + b.d_); s++) iplist.pollLast();
                ed_z = b.z_ + b.d_;
              }
            } else {
              IJ.log("warning");
              iplist.clear();
              st_z = b.z_;
              ed_z = b.z_ + b.d_;
              for (int s = st_z; s < ed_z; s++)
                iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
            }

            if (iplist.size() != b.d_) {
              IJ.log("Stack Error");
              return;
            }

            //						int zz = st_z;

            int bsize = 0;
            byte[] bdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
            Iterator<ImageProcessor> ipite = iplist.iterator();
            while (ipite.hasNext()) {

              //							ImageProcessor tsip = tsst.getProcessor(zz+1);

              ImageProcessor ip = ipite.next();
              ip.setRoi(b.x_, b.y_, b.w_, b.h_);
              if (bdepth == 8) {
                byte[] data = (byte[]) ip.crop().getPixels();
                System.arraycopy(data, 0, bdata, bsize, data.length);
                bsize += data.length;
              } else if (bdepth == 16) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                short[] data = (short[]) ip.crop().getPixels();
                for (short e : data) buffer.putShort(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              } else if (bdepth == 32) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                float[] data = (float[]) ip.crop().getPixels();
                for (float e : data) buffer.putFloat(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              }
            }

            String filename =
                basename
                    + "_Lv"
                    + String.valueOf(l)
                    + "_Ch"
                    + String.valueOf(ch)
                    + "_Fr"
                    + String.valueOf(f)
                    + "_ID"
                    + String.valueOf(i);

            int offset = bytecount;
            int datasize = bdata.length;

            if (filetype == "RAW") {
              int dummy = -1;
              // do nothing
            }
            if (filetype == "JPEG" && bdepth == 8) {
              try {
                DataBufferByte db = new DataBufferByte(bdata, datasize);
                Raster raster = Raster.createPackedRaster(db, b.w_, b.h_ * b.d_, 8, null);
                BufferedImage img =
                    new BufferedImage(b.w_, b.h_ * b.d_, BufferedImage.TYPE_BYTE_GRAY);
                img.setData(raster);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
                String format = "jpg";
                Iterator<javax.imageio.ImageWriter> iter =
                    ImageIO.getImageWritersByFormatName("jpeg");
                javax.imageio.ImageWriter writer = iter.next();
                ImageWriteParam iwp = writer.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality((float) jpeg_quality * 0.01f);
                writer.setOutput(ios);
                writer.write(null, new IIOImage(img, null, null), iwp);
                // ImageIO.write(img, format, baos);
                bdata = baos.toByteArray();
                datasize = bdata.length;
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
            if (filetype == "ZLIB") {
              byte[] tmpdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
              Deflater compresser = new Deflater();
              compresser.setInput(bdata);
              compresser.setLevel(Deflater.DEFAULT_COMPRESSION);
              compresser.setStrategy(Deflater.DEFAULT_STRATEGY);
              compresser.finish();
              datasize = compresser.deflate(tmpdata);
              bdata = tmpdata;
              compresser.end();
            }

            if (bytecount + datasize > sizelimit && bytecount > 0) {
              BufferedOutputStream fis = null;
              try {
                File file = new File(directory + current_dataname);
                fis = new BufferedOutputStream(new FileOutputStream(file));
                fis.write(packed_data, 0, bytecount);
              } catch (IOException e) {
                e.printStackTrace();
                return;
              } finally {
                try {
                  if (fis != null) fis.close();
                } catch (IOException e) {
                  e.printStackTrace();
                  return;
                }
              }
              filecount++;
              current_dataname = base_dataname + "_data" + filecount;
              bytecount = 0;
              offset = 0;
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            } else {
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            }

            Element filenode = doc.createElement("File");
            filenode.setAttribute("filename", current_dataname);
            filenode.setAttribute("channel", String.valueOf(ch));
            filenode.setAttribute("frame", String.valueOf(f));
            filenode.setAttribute("brickID", String.valueOf(i));
            filenode.setAttribute("offset", String.valueOf(offset));
            filenode.setAttribute("datasize", String.valueOf(datasize));
            filenode.setAttribute("filetype", String.valueOf(filetype));

            fsnode.appendChild(filenode);

            curbricknum++;
            IJ.showProgress((double) (curbricknum) / (double) (totalbricknum));
          }
          if (bytecount > 0) {
            BufferedOutputStream fis = null;
            try {
              File file = new File(directory + current_dataname);
              fis = new BufferedOutputStream(new FileOutputStream(file));
              fis.write(packed_data, 0, bytecount);
            } catch (IOException e) {
              e.printStackTrace();
              return;
            } finally {
              try {
                if (fis != null) fis.close();
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
          }
        }
      }

      for (int i = 0; i < bricks.size(); i++) {
        Brick b = bricks.get(i);
        Element bricknode = doc.createElement("Brick");
        bricknode.setAttribute("id", String.valueOf(i));
        bricknode.setAttribute("st_x", String.valueOf(b.x_));
        bricknode.setAttribute("st_y", String.valueOf(b.y_));
        bricknode.setAttribute("st_z", String.valueOf(b.z_));
        bricknode.setAttribute("width", String.valueOf(b.w_));
        bricknode.setAttribute("height", String.valueOf(b.h_));
        bricknode.setAttribute("depth", String.valueOf(b.d_));
        brksnode.appendChild(bricknode);

        Element tboxnode = doc.createElement("tbox");
        tboxnode.setAttribute("x0", String.valueOf(b.tx0_));
        tboxnode.setAttribute("y0", String.valueOf(b.ty0_));
        tboxnode.setAttribute("z0", String.valueOf(b.tz0_));
        tboxnode.setAttribute("x1", String.valueOf(b.tx1_));
        tboxnode.setAttribute("y1", String.valueOf(b.ty1_));
        tboxnode.setAttribute("z1", String.valueOf(b.tz1_));
        bricknode.appendChild(tboxnode);

        Element bboxnode = doc.createElement("bbox");
        bboxnode.setAttribute("x0", String.valueOf(b.bx0_));
        bboxnode.setAttribute("y0", String.valueOf(b.by0_));
        bboxnode.setAttribute("z0", String.valueOf(b.bz0_));
        bboxnode.setAttribute("x1", String.valueOf(b.bx1_));
        bboxnode.setAttribute("y1", String.valueOf(b.by1_));
        bboxnode.setAttribute("z1", String.valueOf(b.bz1_));
        bricknode.appendChild(bboxnode);
      }

      if (l < lv - 1) {
        imp = WindowManager.getImage(lvImgTitle.get(l + 1));
        int[] newdims = imp.getDimensions();
        imageW = newdims[0];
        imageH = newdims[1];
        imageD = newdims[3];
        xspc = orgxspc * ((double) orgW / (double) imageW);
        yspc = orgyspc * ((double) orgH / (double) imageH);
        zspc = orgzspc * ((double) orgD / (double) imageD);
        bdepth = imp.getBitDepth();
      }
    }

    File newXMLfile = new File(directory + basename + ".vvd");
    writeXML(newXMLfile, doc);

    for (int l = 1; l < lv; l++) {
      imp = WindowManager.getImage(lvImgTitle.get(l));
      imp.changes = false;
      imp.close();
    }
  }

  public static Document newXMLDocument() {
    DocumentBuilder dbuilder = null;
    try {
      dbuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
      return null;
    }
    return dbuilder.newDocument();
  }

  public static boolean writeXML(File file, Document document) {

    javax.xml.transform.Transformer transformer = null;
    try {
      transformer = TransformerFactory.newInstance().newTransformer();
    } catch (TransformerConfigurationException e) {
      e.printStackTrace();
      return false;
    }

    transformer.setOutputProperty("indent", "yes");
    transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "2");
    transformer.setOutputProperty("encoding", "UTF-8");

    try {
      transformer.transform(new DOMSource(document), new StreamResult(file));
    } catch (TransformerException e) {
      e.printStackTrace();
      return false;
    }

    return true;
  }

  // Fast way to check for power of two
  public static boolean IsPowerOf2(int n) {
    return (n & (n - 1)) == 0;
  }

  // Returns a number Greater Than or Equal to dim
  // that is an exact power of 2
  // Used for determining what size of texture to
  // allocate to store an image
  public static int Pow2(int dim) {
    if (IsPowerOf2(dim)) return dim;
    int val = 4;
    while (val < dim) val = val << 1;
    return val;
  }
}
  public void run(ImageProcessor ip) {
    String[] imageNames = getOpenImageNames();
    if (imageNames[0] == "None") {
      IJ.error("need at least 2 binary open images");
      return;
    }
    double previousMinOverlap = Prefs.get("BVTB.BinaryFeatureExtractor.minOverlap", 0);
    boolean previousCombine = Prefs.get("BVTB.BinaryFeatureExtractor.combine", false);

    GenericDialog gd = new GenericDialog("Binary Feature Extractor");
    gd.addChoice("Objects image", imageNames, imageNames[0]);
    gd.addChoice("Selector image", imageNames, imageNames[1]);
    gd.addNumericField("Object_overlap in % (0=off)", previousMinOverlap, 0, 9, "");
    gd.addCheckbox("Combine objects and selectors", previousCombine);
    gd.addCheckbox("Count output", true);
    gd.addCheckbox("Analysis tables", false);
    gd.showDialog();
    if (gd.wasCanceled()) {
      return;
    }
    String objectsImgTitle = gd.getNextChoice();
    String selectorsImgTitle = gd.getNextChoice();
    double minOverlap = gd.getNextNumber();
    boolean combineImages = gd.getNextBoolean();
    boolean showCountOutput = gd.getNextBoolean();
    boolean showAnalysis = gd.getNextBoolean();
    if (gd.invalidNumber() || minOverlap < 0 || minOverlap > 100) {
      IJ.error("invalid number");
      return;
    }
    Prefs.set("BVTB.BinaryFeatureExtractor.minOverlap", minOverlap);
    Prefs.set("BVTB.BinaryFeatureExtractor.combine", combineImages);

    if (objectsImgTitle.equals(selectorsImgTitle)) {
      IJ.error("images need to be different");
      return;
    }

    ImagePlus objectsImp = WindowManager.getImage(objectsImgTitle);
    ImageProcessor objectsIP = objectsImp.getProcessor();
    ImagePlus selectorsImp = WindowManager.getImage(selectorsImgTitle);
    ImageProcessor selectorsIP = selectorsImp.getProcessor();

    if (!objectsIP.isBinary() || !selectorsIP.isBinary()) {
      IJ.error("works with 8-bit binary images only");
      return;
    }

    if ((objectsImp.getWidth() != selectorsImp.getWidth())
        || objectsImp.getHeight() != selectorsImp.getHeight()) {
      IJ.error("images need to be of the same size");
      return;
    }

    // close any existing RoiManager before instantiating a new one for this analysis
    RoiManager oldRM = RoiManager.getInstance2();
    if (oldRM != null) {
      oldRM.close();
    }

    RoiManager objectsRM = new RoiManager(true);
    ResultsTable objectsRT = new ResultsTable();
    ParticleAnalyzer analyzeObjects =
        new ParticleAnalyzer(analyzerOptions, measurementFlags, objectsRT, 0.0, 999999999.9);
    analyzeObjects.setRoiManager(objectsRM);

    analyzeObjects.analyze(objectsImp);
    objectsRM.runCommand("Show None");
    int objectNumber = objectsRT.getCounter();

    Roi[] objectRoi = objectsRM.getRoisAsArray();

    ResultsTable measureSelectorsRT = new ResultsTable();
    Analyzer overlapAnalyzer = new Analyzer(selectorsImp, measurementFlags, measureSelectorsRT);

    ImagePlus outputImp =
        IJ.createImage("output", "8-bit black", objectsImp.getWidth(), objectsImp.getHeight(), 1);
    ImageProcessor outputIP = outputImp.getProcessor();

    double[] measuredOverlap = new double[objectNumber];

    outputIP.setValue(255.0);
    for (int o = 0; o < objectNumber; o++) {
      selectorsImp.killRoi();
      selectorsImp.setRoi(objectRoi[o]);
      overlapAnalyzer.measure();
      measuredOverlap[o] = measureSelectorsRT.getValue("%Area", o);
      if (minOverlap != 0.0 && measuredOverlap[o] >= minOverlap) {
        outputIP.fill(objectRoi[o]);
        finalCount++;
      } else if (minOverlap == 0.0 && measuredOverlap[o] > 0.0) {
        outputIP.fill(objectRoi[o]);
        finalCount++;
      }
    }
    // measureSelectorsRT.show("Objects");

    selectorsImp.killRoi();
    RoiManager selectorRM = new RoiManager(true);
    ResultsTable selectorRT = new ResultsTable();
    ParticleAnalyzer.setRoiManager(selectorRM);
    ParticleAnalyzer analyzeSelectors =
        new ParticleAnalyzer(analyzerOptions, measurementFlags, selectorRT, 0.0, 999999999.9);
    analyzeSelectors.analyze(selectorsImp);
    selectorRM.runCommand("Show None");
    int selectorNumber = selectorRT.getCounter();

    if (combineImages) {
      outputImp.updateAndDraw();
      Roi[] selectorRoi = selectorRM.getRoisAsArray();

      ResultsTable measureObjectsRT = new ResultsTable();
      Analyzer selectorAnalyzer = new Analyzer(outputImp, measurementFlags, measureObjectsRT);

      double[] selectorOverlap = new double[selectorNumber];
      outputIP.setValue(255.0);
      for (int s = 0; s < selectorNumber; s++) {
        outputImp.killRoi();
        outputImp.setRoi(selectorRoi[s]);
        selectorAnalyzer.measure();
        selectorOverlap[s] = measureObjectsRT.getValue("%Area", s);
        if (selectorOverlap[s] > 0.0d) {
          outputIP.fill(selectorRoi[s]);
        }
      }
      selectorRoi = null;
      selectorAnalyzer = null;
      measureObjectsRT = null;
    }
    // selectorRT.show("Selectors");
    outputImp.killRoi();
    String outputImageTitle = WindowManager.getUniqueName("Extracted_" + objectsImgTitle);
    outputImp.setTitle(outputImageTitle);
    outputImp.show();
    outputImp.changes = true;

    if (showCountOutput) {
      String[] openTextWindows = WindowManager.getNonImageTitles();
      boolean makeNewTable = true;
      for (int w = 0; w < openTextWindows.length; w++) {
        if (openTextWindows[w].equals("BFE_Results")) {
          makeNewTable = false;
        }
      }

      TextWindow existingCountTable = ResultsTable.getResultsWindow();
      if (makeNewTable) {
        countTable = new ResultsTable();
        countTable.setPrecision(0);
        countTable.setValue("Image", 0, outputImageTitle);
        countTable.setValue("Objects", 0, objectNumber);
        countTable.setValue("Selectors", 0, selectorNumber);
        countTable.setValue("Extracted", 0, finalCount);
        countTable.show("BFE_Results");
      } else {
        IJ.renameResults("BFE_Results", "Results");
        countTable = ResultsTable.getResultsTable();
        countTable.setPrecision(0);
        countTable.incrementCounter();
        countTable.addValue("Image", outputImageTitle);
        countTable.addValue("Objects", objectNumber);
        countTable.addValue("Selectors", selectorNumber);
        countTable.addValue("Extracted", finalCount);
        IJ.renameResults("Results", "BFE_Results");
        countTable.show("BFE_Results");
      }
    }

    if (showAnalysis) {
      ResultsTable extractedRT = new ResultsTable();
      ParticleAnalyzer analyzeExtracted =
          new ParticleAnalyzer(
              ParticleAnalyzer.CLEAR_WORKSHEET | ParticleAnalyzer.RECORD_STARTS,
              measurementFlags,
              extractedRT,
              0.0,
              999999999.9);
      analyzeExtracted.analyze(outputImp);
      objectsRT.show("Objects");
      selectorRT.show("Selectors");
      extractedRT.show("Extracted");
    } else {
      objectsRT = null;
      selectorRT = null;
    }

    objectsRM = null;
    measureSelectorsRT = null;
    analyzeObjects = null;
    overlapAnalyzer = null;
    objectRoi = null;
    selectorRM = null;

    objectsImp.killRoi();
    objectsImp.changes = false;
    selectorsImp.changes = false;
  }
Exemplo n.º 5
0
/**
 * This plugin performs a z-projection of the input stack. Type of output image is same as type of
 * input image.
 *
 * @author Patrick Kelly <*****@*****.**>
 */
public class ZProjector implements PlugIn {
  public static final int AVG_METHOD = 0;
  public static final int MAX_METHOD = 1;
  public static final int MIN_METHOD = 2;
  public static final int SUM_METHOD = 3;
  public static final int SD_METHOD = 4;
  public static final int MEDIAN_METHOD = 5;
  public static final String[] METHODS = {
    "Average Intensity",
    "Max Intensity",
    "Min Intensity",
    "Sum Slices",
    "Standard Deviation",
    "Median"
  };
  private static final String METHOD_KEY = "zproject.method";
  private int method = (int) Prefs.get(METHOD_KEY, AVG_METHOD);

  private static final int BYTE_TYPE = 0;
  private static final int SHORT_TYPE = 1;
  private static final int FLOAT_TYPE = 2;

  public static final String lutMessage =
      "Stacks with inverter LUTs may not project correctly.\n"
          + "To create a standard LUT, invert the stack (Edit/Invert)\n"
          + "and invert the LUT (Image/Lookup Tables/Invert LUT).";

  /** Image to hold z-projection. */
  private ImagePlus projImage = null;

  /** Image stack to project. */
  private ImagePlus imp = null;

  /** Projection starts from this slice. */
  private int startSlice = 1;
  /** Projection ends at this slice. */
  private int stopSlice = 1;
  /** Project all time points? */
  private boolean allTimeFrames = true;

  private String color = "";
  private boolean isHyperstack;
  private int increment = 1;
  private int sliceCount;

  public ZProjector() {}

  /** Construction of ZProjector with image to be projected. */
  public ZProjector(ImagePlus imp) {
    setImage(imp);
  }

  /**
   * Explicitly set image to be projected. This is useful if ZProjection_ object is to be used not
   * as a plugin but as a stand alone processing object.
   */
  public void setImage(ImagePlus imp) {
    this.imp = imp;
    startSlice = 1;
    stopSlice = imp.getStackSize();
  }

  public void setStartSlice(int slice) {
    if (imp == null || slice < 1 || slice > imp.getStackSize()) return;
    startSlice = slice;
  }

  public void setStopSlice(int slice) {
    if (imp == null || slice < 1 || slice > imp.getStackSize()) return;
    stopSlice = slice;
  }

  public void setMethod(int projMethod) {
    method = projMethod;
  }

  /** Retrieve results of most recent projection operation. */
  public ImagePlus getProjection() {
    return projImage;
  }

  public void run(String arg) {
    imp = IJ.getImage();
    int stackSize = imp.getStackSize();
    if (imp == null) {
      IJ.noImage();
      return;
    }

    //  Make sure input image is a stack.
    if (stackSize == 1) {
      IJ.error("Z Project", "Stack required");
      return;
    }

    //  Check for inverting LUT.
    if (imp.getProcessor().isInvertedLut()) {
      if (!IJ.showMessageWithCancel("ZProjection", lutMessage)) return;
    }

    // Set default bounds.
    int channels = imp.getNChannels();
    int frames = imp.getNFrames();
    int slices = imp.getNSlices();
    isHyperstack =
        imp.isHyperStack()
            || (ij.macro.Interpreter.isBatchMode()
                && ((frames > 1 && frames < stackSize) || (slices > 1 && slices < stackSize)));
    boolean simpleComposite = channels == stackSize;
    if (simpleComposite) isHyperstack = false;
    startSlice = 1;
    if (isHyperstack) {
      int nSlices = imp.getNSlices();
      if (nSlices > 1) stopSlice = nSlices;
      else stopSlice = imp.getNFrames();
    } else stopSlice = stackSize;

    // Build control dialog
    GenericDialog gd = buildControlDialog(startSlice, stopSlice);
    gd.showDialog();
    if (gd.wasCanceled()) return;

    if (!imp.lock()) return; // exit if in use
    long tstart = System.currentTimeMillis();
    setStartSlice((int) gd.getNextNumber());
    setStopSlice((int) gd.getNextNumber());
    method = gd.getNextChoiceIndex();
    Prefs.set(METHOD_KEY, method);
    if (isHyperstack) {
      allTimeFrames = imp.getNFrames() > 1 && imp.getNSlices() > 1 ? gd.getNextBoolean() : false;
      doHyperStackProjection(allTimeFrames);
    } else if (imp.getType() == ImagePlus.COLOR_RGB) doRGBProjection(true);
    else doProjection(true);

    if (arg.equals("") && projImage != null) {
      long tstop = System.currentTimeMillis();
      projImage.setCalibration(imp.getCalibration());
      if (simpleComposite) IJ.run(projImage, "Grays", "");
      projImage.show("ZProjector: " + IJ.d2s((tstop - tstart) / 1000.0, 2) + " seconds");
    }

    imp.unlock();
    IJ.register(ZProjector.class);
    return;
  }

  public void doRGBProjection() {
    doRGBProjection(imp.getStack());
  }

  // Added by Marcel Boeglin 2013.09.23
  public void doRGBProjection(boolean handleOverlay) {
    doRGBProjection(imp.getStack());
    Overlay overlay = imp.getOverlay();
    if (handleOverlay && overlay != null) projImage.setOverlay(projectRGBHyperStackRois(overlay));
  }

  private void doRGBProjection(ImageStack stack) {
    ImageStack[] channels = ChannelSplitter.splitRGB(stack, true);
    ImagePlus red = new ImagePlus("Red", channels[0]);
    ImagePlus green = new ImagePlus("Green", channels[1]);
    ImagePlus blue = new ImagePlus("Blue", channels[2]);
    imp.unlock();
    ImagePlus saveImp = imp;
    imp = red;
    color = "(red)";
    doProjection();
    ImagePlus red2 = projImage;
    imp = green;
    color = "(green)";
    doProjection();
    ImagePlus green2 = projImage;
    imp = blue;
    color = "(blue)";
    doProjection();
    ImagePlus blue2 = projImage;
    int w = red2.getWidth(), h = red2.getHeight(), d = red2.getStackSize();
    if (method == SD_METHOD) {
      ImageProcessor r = red2.getProcessor();
      ImageProcessor g = green2.getProcessor();
      ImageProcessor b = blue2.getProcessor();
      double max = 0;
      double rmax = r.getStatistics().max;
      if (rmax > max) max = rmax;
      double gmax = g.getStatistics().max;
      if (gmax > max) max = gmax;
      double bmax = b.getStatistics().max;
      if (bmax > max) max = bmax;
      double scale = 255 / max;
      r.multiply(scale);
      g.multiply(scale);
      b.multiply(scale);
      red2.setProcessor(r.convertToByte(false));
      green2.setProcessor(g.convertToByte(false));
      blue2.setProcessor(b.convertToByte(false));
    }
    RGBStackMerge merge = new RGBStackMerge();
    ImageStack stack2 =
        merge.mergeStacks(w, h, d, red2.getStack(), green2.getStack(), blue2.getStack(), true);
    imp = saveImp;
    projImage = new ImagePlus(makeTitle(), stack2);
  }

  /**
   * Builds dialog to query users for projection parameters.
   *
   * @param start starting slice to display
   * @param stop last slice
   */
  protected GenericDialog buildControlDialog(int start, int stop) {
    GenericDialog gd = new GenericDialog("ZProjection", IJ.getInstance());
    gd.addNumericField("Start slice:", startSlice, 0 /*digits*/);
    gd.addNumericField("Stop slice:", stopSlice, 0 /*digits*/);
    gd.addChoice("Projection type", METHODS, METHODS[method]);
    if (isHyperstack && imp.getNFrames() > 1 && imp.getNSlices() > 1)
      gd.addCheckbox("All time frames", allTimeFrames);
    return gd;
  }

  /** Performs actual projection using specified method. */
  public void doProjection() {
    if (imp == null) return;
    sliceCount = 0;
    if (method < AVG_METHOD || method > MEDIAN_METHOD) method = AVG_METHOD;
    for (int slice = startSlice; slice <= stopSlice; slice += increment) sliceCount++;
    if (method == MEDIAN_METHOD) {
      projImage = doMedianProjection();
      return;
    }

    // Create new float processor for projected pixels.
    FloatProcessor fp = new FloatProcessor(imp.getWidth(), imp.getHeight());
    ImageStack stack = imp.getStack();
    RayFunction rayFunc = getRayFunction(method, fp);
    if (IJ.debugMode == true) {
      IJ.log("\nProjecting stack from: " + startSlice + " to: " + stopSlice);
    }

    // Determine type of input image. Explicit determination of
    // processor type is required for subsequent pixel
    // manipulation.  This approach is more efficient than the
    // more general use of ImageProcessor's getPixelValue and
    // putPixel methods.
    int ptype;
    if (stack.getProcessor(1) instanceof ByteProcessor) ptype = BYTE_TYPE;
    else if (stack.getProcessor(1) instanceof ShortProcessor) ptype = SHORT_TYPE;
    else if (stack.getProcessor(1) instanceof FloatProcessor) ptype = FLOAT_TYPE;
    else {
      IJ.error("Z Project", "Non-RGB stack required");
      return;
    }

    // Do the projection.
    for (int n = startSlice; n <= stopSlice; n += increment) {
      IJ.showStatus("ZProjection " + color + ": " + n + "/" + stopSlice);
      IJ.showProgress(n - startSlice, stopSlice - startSlice);
      projectSlice(stack.getPixels(n), rayFunc, ptype);
    }

    // Finish up projection.
    if (method == SUM_METHOD) {
      fp.resetMinAndMax();
      projImage = new ImagePlus(makeTitle(), fp);
    } else if (method == SD_METHOD) {
      rayFunc.postProcess();
      fp.resetMinAndMax();
      projImage = new ImagePlus(makeTitle(), fp);
    } else {
      rayFunc.postProcess();
      projImage = makeOutputImage(imp, fp, ptype);
    }

    if (projImage == null) IJ.error("Z Project", "Error computing projection.");
  }

  // Added by Marcel Boeglin 2013.09.23
  /**
   * Performs actual projection using specified method. If handleOverlay, adds stack overlay
   * elements from startSlice to stopSlice to projection
   */
  public void doProjection(boolean handleOverlay) {
    doProjection();
    Overlay overlay = imp.getOverlay();
    if (handleOverlay && overlay != null) projImage.setOverlay(projectStackRois(overlay));
  }

  // Added by Marcel Boeglin 2013.09.23
  private Overlay projectStackRois(Overlay overlay) {
    if (overlay == null) return null;
    Overlay overlay2 = new Overlay();
    Roi roi;
    int s;
    for (Roi r : overlay.toArray()) {
      s = r.getPosition();
      roi = (Roi) r.clone();
      if (s >= startSlice && s <= stopSlice || s == 0) {
        roi.setPosition(s);
        overlay2.add(roi);
      }
    }
    return overlay2;
  }

  public void doHyperStackProjection(boolean allTimeFrames) {
    int start = startSlice;
    int stop = stopSlice;
    int firstFrame = 1;
    int lastFrame = imp.getNFrames();
    if (!allTimeFrames) firstFrame = lastFrame = imp.getFrame();
    ImageStack stack = new ImageStack(imp.getWidth(), imp.getHeight());
    int channels = imp.getNChannels();
    int slices = imp.getNSlices();
    if (slices == 1) {
      slices = imp.getNFrames();
      firstFrame = lastFrame = 1;
    }
    int frames = lastFrame - firstFrame + 1;
    increment = channels;
    boolean rgb = imp.getBitDepth() == 24;
    for (int frame = firstFrame; frame <= lastFrame; frame++) {
      for (int channel = 1; channel <= channels; channel++) {
        startSlice = (frame - 1) * channels * slices + (start - 1) * channels + channel;
        stopSlice = (frame - 1) * channels * slices + (stop - 1) * channels + channel;
        if (rgb) doHSRGBProjection(imp);
        else doProjection();
        stack.addSlice(null, projImage.getProcessor());
      }
    }
    projImage = new ImagePlus(makeTitle(), stack);
    projImage.setDimensions(channels, 1, frames);
    if (channels > 1) {
      projImage = new CompositeImage(projImage, 0);
      ((CompositeImage) projImage).copyLuts(imp);
      if (method == SUM_METHOD || method == SD_METHOD)
        ((CompositeImage) projImage).resetDisplayRanges();
    }
    if (frames > 1) projImage.setOpenAsHyperStack(true);
    Overlay overlay = imp.getOverlay();
    if (overlay != null) {
      startSlice = start;
      stopSlice = stop;
      if (imp.getType() == ImagePlus.COLOR_RGB)
        projImage.setOverlay(projectRGBHyperStackRois(overlay));
      else projImage.setOverlay(projectHyperStackRois(overlay));
    }
    IJ.showProgress(1, 1);
  }

  // Added by Marcel Boeglin 2013.09.22
  private Overlay projectRGBHyperStackRois(Overlay overlay) {
    if (overlay == null) return null;
    int frames = projImage.getNFrames();
    int t1 = imp.getFrame();
    Overlay overlay2 = new Overlay();
    Roi roi;
    int c, z, t;
    for (Roi r : overlay.toArray()) {
      c = r.getCPosition();
      z = r.getZPosition();
      t = r.getTPosition();
      roi = (Roi) r.clone();
      if (z >= startSlice && z <= stopSlice || z == 0 || c == 0 || t == 0) {
        if (frames == 1 && t != t1 && t != 0) // current time frame
        continue;
        roi.setPosition(t);
        overlay2.add(roi);
      }
    }
    return overlay2;
  }

  // Added by Marcel Boeglin 2013.09.22
  private Overlay projectHyperStackRois(Overlay overlay) {
    if (overlay == null) return null;
    int t1 = imp.getFrame();
    int channels = projImage.getNChannels();
    int slices = 1;
    int frames = projImage.getNFrames();
    Overlay overlay2 = new Overlay();
    Roi roi;
    int c, z, t;
    int size = channels * slices * frames;
    for (Roi r : overlay.toArray()) {
      c = r.getCPosition();
      z = r.getZPosition();
      t = r.getTPosition();
      roi = (Roi) r.clone();
      if (size == channels) { // current time frame
        if (z >= startSlice && z <= stopSlice && t == t1 || c == 0) {
          roi.setPosition(c);
          overlay2.add(roi);
        }
      } else if (size == frames * channels) { // all time frames
        if (z >= startSlice && z <= stopSlice) roi.setPosition(c, 1, t);
        else if (z == 0) roi.setPosition(c, 0, t);
        else continue;
        overlay2.add(roi);
      }
    }
    return overlay2;
  }

  private void doHSRGBProjection(ImagePlus rgbImp) {
    ImageStack stack = rgbImp.getStack();
    ImageStack stack2 = new ImageStack(stack.getWidth(), stack.getHeight());
    for (int i = startSlice; i <= stopSlice; i++) stack2.addSlice(null, stack.getProcessor(i));
    startSlice = 1;
    stopSlice = stack2.getSize();
    doRGBProjection(stack2);
  }

  private RayFunction getRayFunction(int method, FloatProcessor fp) {
    switch (method) {
      case AVG_METHOD:
      case SUM_METHOD:
        return new AverageIntensity(fp, sliceCount);
      case MAX_METHOD:
        return new MaxIntensity(fp);
      case MIN_METHOD:
        return new MinIntensity(fp);
      case SD_METHOD:
        return new StandardDeviation(fp, sliceCount);
      default:
        IJ.error("Z Project", "Unknown method.");
        return null;
    }
  }

  /** Generate output image whose type is same as input image. */
  private ImagePlus makeOutputImage(ImagePlus imp, FloatProcessor fp, int ptype) {
    int width = imp.getWidth();
    int height = imp.getHeight();
    float[] pixels = (float[]) fp.getPixels();
    ImageProcessor oip = null;

    // Create output image consistent w/ type of input image.
    int size = pixels.length;
    switch (ptype) {
      case BYTE_TYPE:
        oip = imp.getProcessor().createProcessor(width, height);
        byte[] pixels8 = (byte[]) oip.getPixels();
        for (int i = 0; i < size; i++) pixels8[i] = (byte) pixels[i];
        break;
      case SHORT_TYPE:
        oip = imp.getProcessor().createProcessor(width, height);
        short[] pixels16 = (short[]) oip.getPixels();
        for (int i = 0; i < size; i++) pixels16[i] = (short) pixels[i];
        break;
      case FLOAT_TYPE:
        oip = new FloatProcessor(width, height, pixels, null);
        break;
    }

    // Adjust for display.
    // Calling this on non-ByteProcessors ensures image
    // processor is set up to correctly display image.
    oip.resetMinAndMax();

    // Create new image plus object. Don't use
    // ImagePlus.createImagePlus here because there may be
    // attributes of input image that are not appropriate for
    // projection.
    return new ImagePlus(makeTitle(), oip);
  }

  /**
   * Handles mechanics of projection by selecting appropriate pixel array type. We do this rather
   * than using more general ImageProcessor getPixelValue() and putPixel() methods because direct
   * manipulation of pixel arrays is much more efficient.
   */
  private void projectSlice(Object pixelArray, RayFunction rayFunc, int ptype) {
    switch (ptype) {
      case BYTE_TYPE:
        rayFunc.projectSlice((byte[]) pixelArray);
        break;
      case SHORT_TYPE:
        rayFunc.projectSlice((short[]) pixelArray);
        break;
      case FLOAT_TYPE:
        rayFunc.projectSlice((float[]) pixelArray);
        break;
    }
  }

  String makeTitle() {
    String prefix = "AVG_";
    switch (method) {
      case SUM_METHOD:
        prefix = "SUM_";
        break;
      case MAX_METHOD:
        prefix = "MAX_";
        break;
      case MIN_METHOD:
        prefix = "MIN_";
        break;
      case SD_METHOD:
        prefix = "STD_";
        break;
      case MEDIAN_METHOD:
        prefix = "MED_";
        break;
    }
    return WindowManager.makeUniqueName(prefix + imp.getTitle());
  }

  ImagePlus doMedianProjection() {
    IJ.showStatus("Calculating median...");
    ImageStack stack = imp.getStack();
    ImageProcessor[] slices = new ImageProcessor[sliceCount];
    int index = 0;
    for (int slice = startSlice; slice <= stopSlice; slice += increment)
      slices[index++] = stack.getProcessor(slice);
    ImageProcessor ip2 = slices[0].duplicate();
    ip2 = ip2.convertToFloat();
    float[] values = new float[sliceCount];
    int width = ip2.getWidth();
    int height = ip2.getHeight();
    int inc = Math.max(height / 30, 1);
    for (int y = 0; y < height; y++) {
      if (y % inc == 0) IJ.showProgress(y, height - 1);
      for (int x = 0; x < width; x++) {
        for (int i = 0; i < sliceCount; i++) values[i] = slices[i].getPixelValue(x, y);
        ip2.putPixelValue(x, y, median(values));
      }
    }
    if (imp.getBitDepth() == 8) ip2 = ip2.convertToByte(false);
    IJ.showProgress(1, 1);
    return new ImagePlus(makeTitle(), ip2);
  }

  float median(float[] a) {
    Arrays.sort(a);
    int middle = a.length / 2;
    if ((a.length & 1) == 0) // even
    return (a[middle - 1] + a[middle]) / 2f;
    else return a[middle];
  }

  /**
   * Abstract class that specifies structure of ray function. Preprocessing should be done in
   * derived class constructors.
   */
  abstract class RayFunction {
    /** Do actual slice projection for specific data types. */
    public abstract void projectSlice(byte[] pixels);

    public abstract void projectSlice(short[] pixels);

    public abstract void projectSlice(float[] pixels);

    /** Perform any necessary post processing operations, e.g. averging values. */
    public void postProcess() {}
  } // end RayFunction

  /** Compute average intensity projection. */
  class AverageIntensity extends RayFunction {
    private float[] fpixels;
    private int num, len;

    /**
     * Constructor requires number of slices to be projected. This is used to determine average at
     * each pixel.
     */
    public AverageIntensity(FloatProcessor fp, int num) {
      fpixels = (float[]) fp.getPixels();
      len = fpixels.length;
      this.num = num;
    }

    public void projectSlice(byte[] pixels) {
      for (int i = 0; i < len; i++) fpixels[i] += (pixels[i] & 0xff);
    }

    public void projectSlice(short[] pixels) {
      for (int i = 0; i < len; i++) fpixels[i] += pixels[i] & 0xffff;
    }

    public void projectSlice(float[] pixels) {
      for (int i = 0; i < len; i++) fpixels[i] += pixels[i];
    }

    public void postProcess() {
      float fnum = num;
      for (int i = 0; i < len; i++) fpixels[i] /= fnum;
    }
  } // end AverageIntensity

  /** Compute max intensity projection. */
  class MaxIntensity extends RayFunction {
    private float[] fpixels;
    private int len;

    /** Simple constructor since no preprocessing is necessary. */
    public MaxIntensity(FloatProcessor fp) {
      fpixels = (float[]) fp.getPixels();
      len = fpixels.length;
      for (int i = 0; i < len; i++) fpixels[i] = -Float.MAX_VALUE;
    }

    public void projectSlice(byte[] pixels) {
      for (int i = 0; i < len; i++) {
        if ((pixels[i] & 0xff) > fpixels[i]) fpixels[i] = (pixels[i] & 0xff);
      }
    }

    public void projectSlice(short[] pixels) {
      for (int i = 0; i < len; i++) {
        if ((pixels[i] & 0xffff) > fpixels[i]) fpixels[i] = pixels[i] & 0xffff;
      }
    }

    public void projectSlice(float[] pixels) {
      for (int i = 0; i < len; i++) {
        if (pixels[i] > fpixels[i]) fpixels[i] = pixels[i];
      }
    }
  } // end MaxIntensity

  /** Compute min intensity projection. */
  class MinIntensity extends RayFunction {
    private float[] fpixels;
    private int len;

    /** Simple constructor since no preprocessing is necessary. */
    public MinIntensity(FloatProcessor fp) {
      fpixels = (float[]) fp.getPixels();
      len = fpixels.length;
      for (int i = 0; i < len; i++) fpixels[i] = Float.MAX_VALUE;
    }

    public void projectSlice(byte[] pixels) {
      for (int i = 0; i < len; i++) {
        if ((pixels[i] & 0xff) < fpixels[i]) fpixels[i] = (pixels[i] & 0xff);
      }
    }

    public void projectSlice(short[] pixels) {
      for (int i = 0; i < len; i++) {
        if ((pixels[i] & 0xffff) < fpixels[i]) fpixels[i] = pixels[i] & 0xffff;
      }
    }

    public void projectSlice(float[] pixels) {
      for (int i = 0; i < len; i++) {
        if (pixels[i] < fpixels[i]) fpixels[i] = pixels[i];
      }
    }
  } // end MaxIntensity

  /** Compute standard deviation projection. */
  class StandardDeviation extends RayFunction {
    private float[] result;
    private double[] sum, sum2;
    private int num, len;

    public StandardDeviation(FloatProcessor fp, int num) {
      result = (float[]) fp.getPixels();
      len = result.length;
      this.num = num;
      sum = new double[len];
      sum2 = new double[len];
    }

    public void projectSlice(byte[] pixels) {
      int v;
      for (int i = 0; i < len; i++) {
        v = pixels[i] & 0xff;
        sum[i] += v;
        sum2[i] += v * v;
      }
    }

    public void projectSlice(short[] pixels) {
      double v;
      for (int i = 0; i < len; i++) {
        v = pixels[i] & 0xffff;
        sum[i] += v;
        sum2[i] += v * v;
      }
    }

    public void projectSlice(float[] pixels) {
      double v;
      for (int i = 0; i < len; i++) {
        v = pixels[i];
        sum[i] += v;
        sum2[i] += v * v;
      }
    }

    public void postProcess() {
      double stdDev;
      double n = num;
      for (int i = 0; i < len; i++) {
        if (num > 1) {
          stdDev = (n * sum2[i] - sum[i] * sum[i]) / n;
          if (stdDev > 0.0) result[i] = (float) Math.sqrt(stdDev / (n - 1.0));
          else result[i] = 0f;
        } else result[i] = 0f;
      }
    }
  } // end StandardDeviation
} // end ZProjection