Пример #1
0
 public void reduceHyperstack(ImagePlus imp, int factor, boolean reduceSlices) {
   int channels = imp.getNChannels();
   int slices = imp.getNSlices();
   int frames = imp.getNFrames();
   int zfactor = reduceSlices ? factor : 1;
   int tfactor = reduceSlices ? 1 : factor;
   ImageStack stack = imp.getStack();
   ImageStack stack2 = new ImageStack(imp.getWidth(), imp.getHeight());
   boolean virtual = stack.isVirtual();
   int slices2 = slices / zfactor + ((slices % zfactor) != 0 ? 1 : 0);
   int frames2 = frames / tfactor + ((frames % tfactor) != 0 ? 1 : 0);
   int n = channels * slices2 * frames2;
   int count = 1;
   for (int t = 1; t <= frames; t += tfactor) {
     for (int z = 1; z <= slices; z += zfactor) {
       for (int c = 1; c <= channels; c++) {
         int i = imp.getStackIndex(c, z, t);
         IJ.showProgress(i, n);
         ImageProcessor ip = stack.getProcessor(imp.getStackIndex(c, z, t));
         // IJ.log(count++ +"  "+i+" "+c+" "+z+" "+t);
         stack2.addSlice(stack.getSliceLabel(i), ip);
       }
     }
   }
   imp.setStack(stack2, channels, slices2, frames2);
   Calibration cal = imp.getCalibration();
   if (cal.scaled()) cal.pixelDepth *= zfactor;
   if (virtual) imp.setTitle(imp.getTitle());
   IJ.showProgress(1.0);
 }
Пример #2
0
 byte[] getJar(String address) {
   // System.out.println("getJar: "+address);
   byte[] data;
   try {
     URL url = new URL(address);
     IJ.showStatus("Connecting to " + IJ.URL);
     URLConnection uc = url.openConnection();
     int len = uc.getContentLength();
     if (IJ.debugMode) IJ.log("Updater (url): " + address + " " + len);
     if (len <= 0) return null;
     String name = address.contains("wsr") ? "daily build (" : "ij.jar (";
     IJ.showStatus("Downloading " + name + IJ.d2s((double) len / 1048576, 1) + "MB)");
     InputStream in = uc.getInputStream();
     data = new byte[len];
     int n = 0;
     while (n < len) {
       int count = in.read(data, n, len - n);
       if (count < 0) throw new EOFException();
       n += count;
       IJ.showProgress(n, len);
     }
     in.close();
   } catch (IOException e) {
     if (IJ.debugMode) IJ.log("" + e);
     return null;
   }
   if (IJ.debugMode) IJ.wait(6000);
   return data;
 }
 /**
  * Splits the specified RGB stack into three 8-bit grayscale stacks. Deletes the source stack if
  * keepSource is false.
  */
 public static ImageStack[] splitRGB(ImageStack rgb, boolean keepSource) {
   int w = rgb.getWidth();
   int h = rgb.getHeight();
   ImageStack[] channels = new ImageStack[3];
   for (int i = 0; i < 3; i++) channels[i] = new ImageStack(w, h);
   byte[] r, g, b;
   ColorProcessor cp;
   int slice = 1;
   int inc = keepSource ? 1 : 0;
   int n = rgb.getSize();
   for (int i = 1; i <= n; i++) {
     IJ.showStatus(i + "/" + n);
     r = new byte[w * h];
     g = new byte[w * h];
     b = new byte[w * h];
     cp = (ColorProcessor) rgb.getProcessor(slice);
     slice += inc;
     cp.getRGB(r, g, b);
     if (!keepSource) rgb.deleteSlice(1);
     channels[0].addSlice(null, r);
     channels[1].addSlice(null, g);
     channels[2].addSlice(null, b);
     IJ.showProgress((double) i / n);
   }
   return channels;
 }
Пример #4
0
 /** 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;
 }
Пример #5
0
 public void reduceStack(ImagePlus imp, int factor) {
   ImageStack stack = imp.getStack();
   boolean virtual = stack.isVirtual();
   int n = stack.getSize();
   ImageStack stack2 = new ImageStack(stack.getWidth(), stack.getHeight());
   for (int i = 1; i <= n; i += factor) {
     if (virtual) IJ.showProgress(i, n);
     stack2.addSlice(stack.getSliceLabel(i), stack.getProcessor(i));
   }
   imp.setStack(null, stack2);
   if (virtual) {
     IJ.showProgress(1.0);
     imp.setTitle(imp.getTitle());
   }
   Calibration cal = imp.getCalibration();
   if (cal.scaled()) cal.pixelDepth *= factor;
 }
Пример #6
0
 void write16BitStack(OutputStream out, Object[] stack) throws IOException {
   showProgressBar = false;
   for (int i = 0; i < fi.nImages; i++) {
     IJ.showStatus("Writing: " + (i + 1) + "/" + fi.nImages);
     write16BitImage(out, (short[]) stack[i]);
     IJ.showProgress((double) (i + 1) / fi.nImages);
   }
 }
Пример #7
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;
   }
 }
Пример #8
0
    public void run() {
      final int width = this.w;
      final int height = this.h;
      final int depth = this.d;
      final byte[][] daTa = this.data;
      final boolean inverse = inv;
      int zStart, zStop, zBegin, zEnd;
      // float[] sk;
      int n = width;
      if (height > n) n = height;
      if (depth > n) n = depth;
      int noResult = 3 * (n + 1) * (n + 1);
      int[] tempInt = new int[n];
      int[] tempS = new int[n];
      boolean nonempty;
      int test, min, delta;
      for (int j = thread; j < height; j += nThreads) {
        final int wj = width * j;
        IJ.showProgress(j / (1. * height));
        for (int i = 0; i < width; i++) {
          nonempty = false;
          for (int k = 0; k < depth; k++) {
            tempS[k] = (int) s[k][i + wj];
            if (tempS[k] > 0) nonempty = true;
          }
          if (nonempty) {
            zStart = 0;
            while ((zStart < (depth - 1)) && (tempS[zStart] == 0)) zStart++;
            if (zStart > 0) zStart--;
            zStop = depth - 1;
            while ((zStop > 0) && (tempS[zStop] == 0)) zStop--;
            if (zStop < (depth - 1)) zStop++;

            for (int k = 0; k < depth; k++) {
              // Limit to the non-background to save time,
              if (((daTa[k][i + wj] & 255) >= 128) ^ inverse) {
                min = noResult;
                zBegin = zStart;
                zEnd = zStop;
                if (zBegin > k) zBegin = k;
                if (zEnd < k) zEnd = k;
                delta = k - zBegin;
                for (int z = zBegin; z <= zEnd; z++) {
                  test = tempS[z] + delta * delta--;
                  if (test < min) min = test;
                  // min = (test < min) ? test : min;
                }
                tempInt[k] = min;
              }
            }
            for (int k = 0; k < depth; k++) {
              s[k][i + wj] = tempInt[k];
            }
          }
        }
      }
    }
 public static byte[] download(String urlString, String name) {
   int maxLength = 52428800; // 50MB
   URL url = null;
   boolean unknownLength = false;
   byte[] data = null;
   ;
   int n = 0;
   try {
     url = new URL(urlString);
     if (IJ.debugMode) IJ.log("PluginInstaller: " + urlString + "  " + url);
     if (url == null) return null;
     URLConnection uc = url.openConnection();
     int len = uc.getContentLength();
     unknownLength = len < 0;
     if (unknownLength) len = maxLength;
     if (name != null) IJ.showStatus("Downloading " + url.getFile());
     InputStream in = uc.getInputStream();
     data = new byte[len];
     int lenk = len / 1024;
     while (n < len) {
       int count = in.read(data, n, len - n);
       if (count < 0) break;
       n += count;
       if (name != null)
         IJ.showStatus("Downloading " + name + " (" + (n / 1024) + "/" + lenk + "k)");
       IJ.showProgress(n, len);
     }
     in.close();
   } catch (Exception e) {
     String msg = "" + e;
     if (!msg.contains("://")) msg += "\n   " + urlString;
     IJ.error("Plugin Installer", msg);
     return null;
   } finally {
     IJ.showProgress(1.0);
   }
   if (name != null) IJ.showStatus("");
   if (unknownLength) {
     byte[] data2 = data;
     data = new byte[n];
     for (int i = 0; i < n; i++) data[i] = data2[i];
   }
   return data;
 }
Пример #10
0
  public void run(String arg) {
    int[] wList = WindowManager.getIDList();
    if (wList == null) {
      IJ.error("No images are open.");
      return;
    }

    double thalf = 0.5;
    boolean keep;

    GenericDialog gd = new GenericDialog("Bleach correction");

    gd.addNumericField("t½:", thalf, 1);
    gd.addCheckbox("Keep source stack:", true);
    gd.showDialog();
    if (gd.wasCanceled()) return;

    long start = System.currentTimeMillis();
    thalf = gd.getNextNumber();
    keep = gd.getNextBoolean();
    if (keep) IJ.run("Duplicate...", "title='Bleach corrected' duplicate");
    ImagePlus imp1 = WindowManager.getCurrentImage();
    int d1 = imp1.getStackSize();
    double v1, v2;
    int width = imp1.getWidth();
    int height = imp1.getHeight();
    ImageProcessor ip1, ip2, ip3;

    int slices = imp1.getStackSize();
    ImageStack stack1 = imp1.getStack();
    ImageStack stack2 = imp1.getStack();
    int currentSlice = imp1.getCurrentSlice();

    for (int n = 1; n <= slices; n++) {
      ip1 = stack1.getProcessor(n);
      ip3 = stack1.getProcessor(1);
      ip2 = stack2.getProcessor(n);
      for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
          v1 = ip1.getPixelValue(x, y);
          v2 = ip3.getPixelValue(x, y);

          // =B8/(EXP(-C$7*A8))
          v1 = (v1 / Math.exp(-n * thalf));
          ip2.putPixelValue(x, y, v1);
        }
      }
      IJ.showProgress((double) n / slices);
      IJ.showStatus(n + "/" + slices);
    }

    // stack2.show();
    imp1.updateAndDraw();
  }
Пример #11
0
  /** 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.");
  }
Пример #12
0
 void write16BitVirtualStack(OutputStream out, VirtualStack virtualStack) throws IOException {
   showProgressBar = false;
   boolean flip = "FlipTheseImages".equals(fi.fileName);
   for (int i = 1; i <= fi.nImages; i++) {
     IJ.showStatus("Writing: " + i + "/" + fi.nImages);
     ImageProcessor ip = virtualStack.getProcessor(i);
     if (flip) ip.flipVertical();
     short[] pixels = (short[]) ip.getPixels();
     write16BitImage(out, pixels);
     IJ.showProgress((double) i / fi.nImages);
   }
 }
Пример #13
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;
 }
Пример #14
0
  private final void renderCubeFaces(final double hfov, final double vfov) {
    /* fragile, but that's not public API and we know what we're doing... */
    final double cubeSize = frontSource.getWidth() - 1;

    /* prepare extended image */
    ipSource =
        ip.createProcessor(
            hfov == 2.0 * Math.PI ? imp.getWidth() + 1 : imp.getWidth(),
            vfov == Math.PI ? imp.getHeight() + 1 : imp.getHeight());
    prepareExtendedImage(imp.getProcessor(), ipSource);

    /* render cube faces */
    final EquirectangularProjection q = p.clone();
    q.resetOrientation();
    q.setTargetWidth(cubeSize);
    q.setTargetHeight(cubeSize);
    q.setF(0.5f);

    final InverseTransformMapping<EquirectangularProjection> qMapping =
        new InverseTransformMapping<EquirectangularProjection>(q);

    IJ.showStatus("Rendering cube faces...");
    IJ.showProgress(0, 6);
    qMapping.mapInterpolated(ipSource, frontSource);
    IJ.showProgress(1, 6);
    q.pan(Math.PI);
    qMapping.mapInterpolated(ipSource, backSource);
    IJ.showProgress(2, 6);
    q.resetOrientation();
    q.pan(Math.PI / 2);
    qMapping.mapInterpolated(ipSource, leftSource);
    IJ.showProgress(3, 6);
    q.resetOrientation();
    q.pan(-Math.PI / 2);
    qMapping.mapInterpolated(ipSource, rightSource);
    IJ.showProgress(4, 6);
    q.resetOrientation();
    q.tilt(-Math.PI / 2);
    qMapping.mapInterpolated(ipSource, topSource);
    IJ.showProgress(5, 6);
    q.resetOrientation();
    q.tilt(Math.PI / 2);
    qMapping.mapInterpolated(ipSource, bottomSource);
    IJ.showProgress(6, 6);

    if (showCubefaces) {
      new ImagePlus("front", frontSource).show();
      new ImagePlus("back", backSource).show();
      new ImagePlus("left", leftSource).show();
      new ImagePlus("right", rightSource).show();
      new ImagePlus("top", topSource).show();
      new ImagePlus("bottom", bottomSource).show();
    }
  }
Пример #15
0
 ImagePlus openDicomStack(ZipInputStream zis, ZipEntry entry) throws IOException {
   ImagePlus imp = null;
   int count = 0;
   ImageStack stack = null;
   while (true) {
     if (count > 0) entry = zis.getNextEntry();
     if (entry == null) break;
     String name = entry.getName();
     ImagePlus imp2 = null;
     if (name.endsWith(".dcm")) {
       ByteArrayOutputStream out = new ByteArrayOutputStream();
       byte[] buf = new byte[4096];
       int len, byteCount = 0, progress = 0;
       while (true) {
         len = zis.read(buf);
         if (len < 0) break;
         out.write(buf, 0, len);
         byteCount += len;
         // IJ.showProgress((double)(byteCount%fileSize)/fileSize);
       }
       byte[] bytes = out.toByteArray();
       out.close();
       InputStream is = new ByteArrayInputStream(bytes);
       DICOM dcm = new DICOM(is);
       dcm.run(name);
       imp2 = dcm;
       is.close();
     }
     zis.closeEntry();
     if (imp2 == null) continue;
     count++;
     String label = imp2.getTitle();
     String info = (String) imp2.getProperty("Info");
     if (info != null) label += "\n" + info;
     if (count == 1) {
       imp = imp2;
       imp.getStack().setSliceLabel(label, 1);
     } else {
       stack = imp.getStack();
       stack.addSlice(label, imp2.getProcessor());
       imp.setStack(stack);
     }
   }
   zis.close();
   IJ.showProgress(1.0);
   if (count == 0)
     throw new IOException("This ZIP archive does not appear to contain any .dcm files");
   return imp;
 }
Пример #16
0
 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);
 }
Пример #17
0
 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);
 }
Пример #18
0
 public void run() {
   final int width = this.w;
   final int height = this.h;
   final int depth = this.d;
   final boolean inverse = inv;
   float[] sk;
   int n = width;
   if (height > n) n = height;
   if (depth > n) n = depth;
   int noResult = 3 * (n + 1) * (n + 1);
   boolean[] background = new boolean[n];
   int test, min;
   for (int k = thread; k < depth; k += nThreads) {
     IJ.showProgress(k / (1. * depth));
     sk = s[k];
     final byte[] dk = data[k];
     for (int j = 0; j < height; j++) {
       final int wj = width * j;
       for (int i = 0; i < width; i++) {
         background[i] = ((dk[i + wj] & 255) < 128) ^ inverse;
       }
       for (int i = 0; i < width; i++) {
         min = noResult;
         for (int x = i; x < width; x++) {
           if (background[x]) {
             test = i - x;
             test *= test;
             min = test;
             break;
           }
         }
         for (int x = i - 1; x >= 0; x--) {
           if (background[x]) {
             test = i - x;
             test *= test;
             if (test < min) min = test;
             break;
           }
         }
         sk[i + wj] = min;
       }
     }
   }
 } // run
Пример #19
0
 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);
 }
Пример #20
0
 // extract range of slices
 ImagePlus stackRange(ImagePlus imp, int first, int last, int inc, String title) throws Exception {
   ImageStack stack = imp.getStack();
   ImageStack stack2 = null;
   Roi roi = imp.getRoi();
   for (int i = first, j = 0; i <= last; i += inc) {
     // IJ.log(first+" "+last+" "+inc+" "+i);
     IJ.showProgress(i - first, last - first);
     int currSlice = i - j;
     ImageProcessor ip2 = stack.getProcessor(currSlice);
     // ip2.setRoi(roi);
     // ip2 = ip2.crop();
     if (stack2 == null) stack2 = new ImageStack(ip2.getWidth(), ip2.getHeight());
     stack2.addSlice(stack.getSliceLabel(currSlice), ip2);
   }
   ImagePlus substack = imp.createImagePlus();
   substack.setStack(title, stack2);
   substack.setCalibration(imp.getCalibration());
   return substack;
 }
  public ImageStack expandStack(ImageStack stackOld, int wNew, int hNew, int xOff, int yOff) {
    int nFrames = stackOld.getSize();
    ImageProcessor ipOld = stackOld.getProcessor(1);
    java.awt.Color colorBack = Toolbar.getBackgroundColor();

    ImageStack stackNew = new ImageStack(wNew, hNew, stackOld.getColorModel());
    ImageProcessor ipNew;

    for (int i = 1; i <= nFrames; i++) {
      IJ.showProgress((double) i / nFrames);
      ipNew = ipOld.createProcessor(wNew, hNew);
      if (zeroFill) ipNew.setValue(0.0);
      else ipNew.setColor(colorBack);
      ipNew.fill();
      ipNew.insert(stackOld.getProcessor(i), xOff, yOff);
      stackNew.addSlice(stackOld.getSliceLabel(i), ipNew);
    }
    return stackNew;
  }
  public void runLipschitz(ImageProcessor ip) {
    if (IJ.escapePressed()) return;
    breaked = false;
    Date d1, d2;
    d1 = new Date();

    IJ.showStatus("Initializing...");
    m_stack_out = m_imp.createEmptyStack();
    ImagePlus imp2 = null;

    for (int i = 0; ((i < m_scount) && (!breaked)); i++) {
      if (m_scount > 1) {
        ip = m_stack.getProcessor(i + 1);
      }
      iptmp = ip.createProcessor(ImageWidth, ImageHeight);
      iptmp.copyBits(ip, 0, 0, Blitter.COPY);

      IJ.showStatus("Filtering " + (i + 1) + "/" + m_scount + " slice.");

      Lipschitz2D(iptmp);

      m_stack_out.addSlice(m_imp.getShortTitle() + " " + (i + 1) + "/" + m_scount, iptmp);

      if (breaked = IJ.escapePressed()) IJ.beep();
    }

    imp2 =
        new ImagePlus(
            m_imp.getShortTitle()
                + " Filtered (Lipschitz) Slope:"
                + m_Slope
                + " "
                + ((m_Down) ? " -Down" : " ")
                + " "
                + ((m_TopHat) ? " -TopHat" : " ")
                + ((breaked) ? " -INTERUPTED" : ""),
            m_stack_out);
    imp2.show();
    imp2.updateAndDraw();
    IJ.showProgress(1.0);
  } // end of 'runLipschitz' method
Пример #23
0
 public void run() {
   final int width = this.w;
   final int height = this.h;
   final int depth = this.d;
   float[] sk;
   int n = width;
   if (height > n) n = height;
   if (depth > n) n = depth;
   int noResult = 3 * (n + 1) * (n + 1);
   int[] tempInt = new int[n];
   int[] tempS = new int[n];
   boolean nonempty;
   int test, min, delta;
   for (int k = thread; k < depth; k += nThreads) {
     IJ.showProgress(k / (1. * depth));
     sk = s[k];
     for (int i = 0; i < width; i++) {
       nonempty = false;
       for (int j = 0; j < height; j++) {
         tempS[j] = (int) sk[i + width * j];
         if (tempS[j] > 0) nonempty = true;
       }
       if (nonempty) {
         for (int j = 0; j < height; j++) {
           min = noResult;
           delta = j;
           for (int y = 0; y < height; y++) {
             test = tempS[y] + delta * delta--;
             if (test < min) min = test;
           }
           tempInt[j] = min;
         }
         for (int j = 0; j < height; j++) {
           sk[i + width * j] = tempInt[j];
         }
       }
     }
   }
 } // run
Пример #24
0
  /**
   * Reduce error in thickness quantitation by trimming the one pixel overhang in the thickness map
   *
   * @param imp Binary input image
   * @param impLTC Thickness map
   * @param inv true if calculating thickness of background, false for foreground
   * @return Thickness map with pixels masked by input image
   */
  private ImagePlus trimOverhang(ImagePlus imp, ImagePlus impLTC, boolean inv) {
    final int w = imp.getWidth();
    final int h = imp.getHeight();
    final int d = imp.getImageStackSize();

    final ImageStack stack = imp.getImageStack();
    final ImageStack mapStack = impLTC.getImageStack();

    final int keepValue = inv ? 0 : 255;
    ImageProcessor ip = new ByteProcessor(w, h);
    ImageProcessor map = new FloatProcessor(w, h);
    for (int z = 1; z <= d; z++) {
      IJ.showStatus("Masking thickness map...");
      IJ.showProgress(z, d);
      ip = stack.getProcessor(z);
      map = mapStack.getProcessor(z);
      for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
          if (ip.get(x, y) != keepValue) map.set(x, y, 0);
        }
      }
    }
    return impLTC;
  }
Пример #25
0
 byte[] getJar(String address) {
   byte[] data;
   boolean gte133 = version().compareTo("1.33u") >= 0;
   try {
     URL url = new URL(address);
     URLConnection uc = url.openConnection();
     int len = uc.getContentLength();
     String name = address.endsWith("ij/ij.jar") ? "daily build" : "ij.jar";
     IJ.showStatus("Downloading ij.jar (" + IJ.d2s((double) len / 1048576, 1) + "MB)");
     InputStream in = uc.getInputStream();
     data = new byte[len];
     int n = 0;
     while (n < len) {
       int count = in.read(data, n, len - n);
       if (count < 0) throw new EOFException();
       n += count;
       if (gte133) IJ.showProgress(n, len);
     }
     in.close();
   } catch (IOException e) {
     return null;
   }
   return data;
 }
  public void OpenCLRun(double[] motionfield) {
    try {
      while (projectionsAvailable.size() > 0) {
        Thread.sleep(CONRAD.INVERSE_SPEEDUP);
        if (showStatus) {
          float status = (float) (1.0 / projections.size());
          if (largeVolumeMode) {
            IJ.showStatus("Streaming Projections to OpenCL Buffer");
          } else {
            IJ.showStatus("Backprojecting with OpenCL");
          }
          IJ.showProgress(status);
        }
        if (!largeVolumeMode) {
          workOnProjectionData(motionfield);
        } else {
          checkProjectionData();
        }
      }
      //			System.out.println("large Volume " + largeVolumeMode);
      if (largeVolumeMode) {
        // we have collected all projections.
        // now we can reconstruct subvolumes and stich them together.
        int reconDimensionZ = getGeometry().getReconDimensionZ();
        double voxelSpacingX = getGeometry().getVoxelSpacingX();
        double voxelSpacingY = getGeometry().getVoxelSpacingY();
        double voxelSpacingZ = getGeometry().getVoxelSpacingZ();
        useVOImap = false;
        initialize(projections.get(0));
        double originalOffsetZ = offsetZ;
        double originalReconDimZ = reconDimensionZ;
        reconDimensionZ = subVolumeZ;
        int maxProjectionNumber = projections.size();
        float all = nSteps * maxProjectionNumber * 2;
        for (int n = 0; n < nSteps; n++) { // For each subvolume
          // set all to 0;
          Arrays.fill(h_volume, 0);

          volumePointer.getBuffer().rewind();
          volumePointer.getBuffer().put(h_volume);
          volumePointer.getBuffer().rewind();
          commandQueue.putWriteBuffer(volumePointer, true).finish();

          offsetZ = originalOffsetZ - (reconDimensionZ * voxelSpacingZ * n);
          for (int p = 0; p < maxProjectionNumber; p++) { // For all projections
            float currentStep = (n * maxProjectionNumber * 2) + p;
            if (showStatus) {
              IJ.showStatus("Backprojecting with OpenCL");
              IJ.showProgress(currentStep / all);
            }
            // System.out.println("Current: " + p);
            float respoffset = (float) Math.round(motionfield[p] / voxelSpacingZ);
            try {
              projectSingleProjection(p, reconDimensionZ, respoffset);
            } catch (Exception e) {
              System.out.println("Backprojection of projection " + p + " was not successful.");
              e.printStackTrace();
            }
          }
          // Gather volume
          commandQueue.putReadBuffer(volumePointer, true).finish();
          volumePointer.getBuffer().rewind();
          volumePointer.getBuffer().get(h_volume);
          volumePointer.getBuffer().rewind();

          // move data to ImagePlus;
          if (projectionVolume != null) {
            for (int k = 0; k < reconDimensionZ; k++) {
              int index = (n * subVolumeZ) + k;
              if (showStatus) {
                float currentStep = (n * maxProjectionNumber * 2) + maxProjectionNumber + k;
                IJ.showStatus("Fetching Volume from OpenCL");
                IJ.showProgress(currentStep / all);
              }
              if (index < originalReconDimZ) {
                for (int j = 0; j < projectionVolume.getSize()[1]; j++) {
                  for (int i = 0; i < projectionVolume.getSize()[0]; i++) {
                    float value =
                        h_volume[
                            (((projectionVolume.getSize()[1] * k) + j)
                                    * projectionVolume.getSize()[0])
                                + i];
                    double[][] voxel = new double[4][1];
                    voxel[0][0] = (voxelSpacingX * i) - offsetX;
                    voxel[1][0] = (voxelSpacingY * j) - offsetY;
                    voxel[2][0] = (voxelSpacingZ * index) - originalOffsetZ;

                    // exception for the case "interestedInVolume == null" and largeVolume is
                    // enabled
                    if (interestedInVolume == null) {
                      projectionVolume.setAtIndex(i, j, index, value);
                    } else {
                      if (interestedInVolume.contains(voxel[0][0], voxel[1][0], voxel[2][0])) {
                        projectionVolume.setAtIndex(i, j, index, value);
                      } else {
                        projectionVolume.setAtIndex(i, j, index, 0);
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }

    } catch (InterruptedException e) {

      e.printStackTrace();
    }
    if (showStatus) IJ.showProgress(1.0);
    unload();
    if (debug) System.out.println("Unloaded");
  }
Пример #27
0
  public void calAutoCorrelation(
      int
          nRefType) { // computing the cross correlation coefficient between pixel values of points
                      // separated by the radius of rings
    m_nRefType = nRefType;
    int numRings = m_cvRings.size();
    calRefPixels();
    m_cPixelMeanSems = CommonStatisticsMethods.buildMeanSem(m_pnPixelsLR);
    int len;

    double mean = m_cPixelMeanSems.mean, sem2 = m_cPixelMeanSems.sem2;
    double medianMean[] = new double[numRings - 1];
    double medianSem2[] = new double[numRings - 1];

    double crossProduct[] = new double[numRings - 1];
    double numCrossPairs[] = new double[numRings - 1];
    double crossProduct_median[] = new double[numRings - 1];
    double numCrossPairs_median[] = new double[numRings - 1];

    ArrayList<Double> medians[] = new ArrayList[numRings - 1];
    int i, j, pixel0;

    for (i = 0; i < numRings - 1; i++) {
      crossProduct[i] = 0;
      numCrossPairs[i] = 0;
      crossProduct_median[i] = 0;
      numCrossPairs_median[i] = 0;
      medianMean[i] = 0;
      medianSem2[i] = 0;
      medians[i] = new ArrayList();
    }

    int[][] pixels_LMC = new int[h][w];

    ImageShape shape;
    ArrayList<Point> points = new ArrayList();
    ArrayList<Point> scanningTrace = new ArrayList();

    double dp, median;
    Point p0, p;
    int index = 0, y0 = 0, y;
    Histogram hist;
    int nRef, mean1;
    while (true) {
      p0 = new Point(m_cIMSC.getPosition());
      y = p0.y;
      scanningTrace.add(p0);
      pixel0 = m_pnPixelsLR[p0.y][p0.x];
      nRef = getRefPixel(p0);
      dp = pixel0 - mean;
      CommonMethods.fillHistograms(m_pnPixels, nRef, m_cvRings, p0, m_cvHists);
      for (i = 0; i < numRings - 1; i++) {
        shape = m_cvRings.get(i);
        shape.setCenter(p0);
        shape.setFrameRanges(
            new intRange(p0.x, w - 1),
            new intRange(
                p0.y,
                h - 1)); // this is to avoid double counting the pair of points with given distance
        shape.getInnerPoints(points);
        shape.setFrameRanges(new intRange(0, w - 1), new intRange(0, h - 1));
        len = points.size();
        for (j = 0; j < len; j++) {
          p = points.get(j);
          crossProduct[i] += dp * (m_pnPixels[p.y][p.x] - nRef - mean);
        }
        numCrossPairs[i] += len;

        numCrossPairs_median[i] += 1;

        hist = m_cvHists.get(i);
        median = hist.getPercentileValue();
        medianMean[i] += median;
        medianSem2[i] += median * median;
        medians[i].add(median);
        if (y > y0) {
          IJ.showStatus("computing autocorrelation: " + PrintAssist.ToString(y) + "-th line");
          IJ.showProgress(y / h);
          y0 = y;
        }
      }
      if (m_cIMSC.done()) break;
      m_cIMSC.move();
      index++;
    }
    double dAutoCorr_mean, meanMedian, cp;
    MeanSem0 ms = new MeanSem0();
    int num;
    for (i = 0; i < numRings - 1; i++) {
      m_pdAutoCorr_mean[i] = crossProduct[i] / (Math.sqrt(sem2 * sem2) * (numCrossPairs[i]));
      num = medians[i].size();
      medianMean[i] /= num;
      medianSem2[i] /= num;
      ms.updateMeanSquareSum(num, medianMean[i], medianSem2[i]);
      meanMedian = ms.mean;
      cp = 0;
      for (j = 0; j < num; j++) {
        p = scanningTrace.get(j);
        cp += (m_pnPixelsLR[p.y][p.x] - mean) * (medians[i].get(j) - meanMedian);
      }
      m_pdAutoCorr_median[i] = cp / (Math.sqrt(sem2 * ms.sem2) * (num));
    }
  }
Пример #28
0
 protected void updateStatus() {
   double totalDone = 0;
   for (double p : tasksProportionsDone) totalDone += p;
   IJ.showProgress(totalDone / totalTasks);
 }
Пример #29
0
 @Override
 public void statusUpdated(StatusEvent evt) {
   IJ.showStatus(evt.getStatusMessage());
   IJ.showProgress(evt.getProgressValue(), evt.getProgressMaximum());
 }
Пример #30
0
 public void done() {
   IJ.showProgress(1.0);
 }