Ejemplo n.º 1
0
 public void splitRGB(ImagePlus imp) {
   boolean keepSource = IJ.altKeyDown();
   String title = imp.getTitle();
   Calibration cal = imp.getCalibration();
   int pos = imp.getCurrentSlice();
   ImageStack[] channels = splitRGB(imp.getStack(), keepSource);
   if (!keepSource) {
     imp.unlock();
     imp.changes = false;
     imp.close();
   }
   ImagePlus rImp = new ImagePlus(title + " (red)", channels[0]);
   rImp.setCalibration(cal);
   rImp.show();
   rImp.setSlice(pos);
   if (IJ.isMacOSX()) IJ.wait(500);
   ImagePlus gImp = new ImagePlus(title + " (green)", channels[1]);
   gImp.setCalibration(cal);
   gImp.show();
   gImp.setSlice(pos);
   if (IJ.isMacOSX()) IJ.wait(500);
   ImagePlus bImp = new ImagePlus(title + " (blue)", channels[2]);
   bImp.setCalibration(cal);
   bImp.show();
   bImp.setSlice(pos);
 }
Ejemplo n.º 2
0
 public StackWindow(ImagePlus imp, ImageCanvas ic) {
   super(imp, ic);
   addScrollbars(imp);
   addMouseWheelListener(this);
   if (sliceSelector == null && this.getClass().getName().indexOf("Image5D") != -1)
     sliceSelector = new Scrollbar(); // prevents Image5D from crashing
   // IJ.log(nChannels+" "+nSlices+" "+nFrames);
   pack();
   ic = imp.getCanvas();
   if (ic != null) ic.setMaxBounds();
   show();
   int previousSlice = imp.getCurrentSlice();
   if (previousSlice > 1 && previousSlice <= imp.getStackSize()) imp.setSlice(previousSlice);
   else imp.setSlice(1);
   thread = new Thread(this, "zSelector");
   thread.start();
 }
Ejemplo n.º 3
0
  public static ImagePlus scale(ImagePlus imp, double factor) {

    int newWidth = (int) Math.round(imp.getWidth() * factor);
    int newHeight = (int) Math.round(imp.getHeight() * factor);
    ImageStack is = new ImageStack(newWidth, newHeight);
    for (int i = 0; i < imp.getNSlices(); i++) {
      imp.setSlice(i);
      ImageProcessor ic = imp.getProcessor().resize(newWidth);
      is.addSlice(ic);
    }
    ImagePlus resImp = new ImagePlus(imp.getTitle() + "_scaled", is);
    return (resImp);
  }
 public void run(ImageProcessor ip) {
   if (canceled) return;
   slice++;
   if (imp.getStackSize() > 1 && processStack) imp.setSlice(slice);
   if (imp.getType() == ImagePlus.COLOR_RGB) {
     ip = (ImageProcessor) imp.getProperty("Mask");
     ip.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE);
   }
   if (!analyze(imp, ip)) canceled = true;
   if (slice == imp.getStackSize()) {
     imp.updateAndDraw();
     if (saveRoi != null) imp.setRoi(saveRoi);
   }
 }
  /**
   * Can be called with values[ 3 ], i.e. [initialsigma, sigma2, threshold] or values[ 2 ], i.e.
   * [initialsigma, threshold]
   *
   * <p>The results are stored in the same array. If called with values[ 2 ], sigma2 changing will
   * be disabled
   *
   * @param text - the text which is shown when asking for the file
   * @param values - the initial values and also contains the result
   * @param sigmaMax - the maximal sigma allowed by the interactive app
   * @return {@link InteractiveDoG} - the instance for querying additional parameters
   */
  public static InteractiveDoG getInteractiveDoGParameters(
      final ImagePlus imp, final int channel, final double values[], final float sigmaMax) {
    if (imp.isDisplayedHyperStack())
      imp.setPosition(imp.getStackIndex(channel + 1, imp.getNSlices() / 2 + 1, 1));
    else imp.setSlice(imp.getStackIndex(channel + 1, imp.getNSlices() / 2 + 1, 1));

    imp.setRoi(0, 0, imp.getWidth() / 3, imp.getHeight() / 3);

    final InteractiveDoG idog = new InteractiveDoG(imp, channel);
    idog.setSigmaMax(sigmaMax);
    idog.setLookForMaxima(defaultInteractiveMaxima);
    idog.setLookForMinima(defaultInteractiveMinima);

    if (values.length == 2) {
      idog.setSigma2isAdjustable(false);
      idog.setInitialSigma((float) values[0]);
      idog.setThreshold((float) values[1]);
    } else {
      idog.setInitialSigma((float) values[0]);
      idog.setThreshold((float) values[2]);
    }

    idog.run(null);

    while (!idog.isFinished()) SimpleMultiThreading.threadWait(100);

    if (values.length == 2) {
      values[0] = idog.getInitialSigma();
      values[1] = idog.getThreshold();
    } else {
      values[0] = idog.getInitialSigma();
      values[1] = idog.getSigma2();
      values[2] = idog.getThreshold();
    }

    // remove the roi
    imp.killRoi();

    defaultInteractiveMaxima = idog.getLookForMaxima();
    defaultInteractiveMinima = idog.getLookForMinima();

    return idog;
  }
Ejemplo n.º 6
0
 void applyStack() {
   // int minKeepH = minHue, maxKeepH = maxHue; //GL not needed?
   // int minKeepS = minSat, maxKeepS = maxSat;
   // int minKeepB = minBri, maxKeepB = maxBri;
   for (int i = 1; i <= numSlices; i++) {
     imp.setSlice(i);
     if (!checkImage()) {
       IJ.beep();
       IJ.showStatus("No Image");
       return;
     }
     //	minHue = minKeepH;
     //	maxHue = maxKeepH;
     //	minSat = minKeepS;
     //	maxSat = maxKeepS;
     //	minBri = minKeepB;
     //	maxBri = maxKeepB;
     apply(imp, ip);
   }
 }
Ejemplo n.º 7
0
  public void showRois3D() {
    registerActiveImage();
    if (currentImage == null) return;
    // verifier que l'image active a les memes dimentions
    Object[] os = this.list.getSelectedValues();

    if (os.length == 1) {
      mcib3d.geom.Object3D o = ((Object3DGui) os[0]).getObject3D();
      currentImage.setSlice((o.getZmax() + o.getZmin()) / 2 + 1);
    }
    int nSlices = currentImage.getNSlices();

    currentROIs = new HashMap<Integer, Roi>(nSlices);
    // stores the roi mask to save memory..
    if (roiMask == null || !roiMask.sameDimentions(currentImage)) {
      roiMask = new ImageByte("mask", currentImage.getWidth(), currentImage.getHeight(), nSlices);
    } else {
      roiMask.erase();
    }
    ImageStack maskStack = roiMask.getImageStack();
    Object3DGui obj;
    for (Object o : os) {
      obj = (Object3DGui) o;
      obj.getObject3D().draw(maskStack, 255);
    }
    // roiMask.show();

    for (int i = 1; i <= nSlices; i++) {
      ImagePlus im = new ImagePlus("mask", maskStack.getProcessor(i));
      im.getProcessor().setThreshold(1, 255, ImageProcessor.NO_LUT_UPDATE);
      ThresholdToSelection tts = new ThresholdToSelection();
      tts.setup("", im);
      tts.run(im.getProcessor());
      Roi r = im.getRoi();
      if (r != null) currentROIs.put(i, r);
    }
    updateRoi();
  }
Ejemplo n.º 8
0
  /**
   * Read VoxelMatrix file
   *
   * @param path input file name with path
   * @return read image or null if error
   */
  public static ImagePlus read(String path) {
    if (null == path) return null;

    ImagePlus imp = new ImagePlus();

    try {
      // create file input & data input stream
      FileInputStream fis = new FileInputStream(path);
      DataInputStream dis = new DataInputStream(fis);

      int size1, size2, size3;
      size1 = reverse(dis.readInt()); // 0
      size2 = reverse(dis.readInt()); // 0
      size3 = reverse(dis.readInt()); // 0

      // Distinguish between versions: previous versions of VM files used 3 values
      if (size1 > 0 && size2 > 0 && size3 > 0) {
        // old version type = int;
        imp = readOldFormat(path, dis, size1, size2, size3);
        fis.close();
        dis.close();
        if (size3 > 1) {
          imp.setSlice(size3 / 2);
          ImageProcessor ip = imp.getProcessor();
          ip.resetMinAndMax();
          imp.setDisplayRange(ip.getMin(), ip.getMax());
        }
      } else {
        imp = openNewFormat(path, dis);
        fis.close();
        dis.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
    return imp;
  }
Ejemplo n.º 9
0
  private boolean track(
      ImagePlus siPlus, ArrayList<Point2D.Double> xyPoints, ArrayList<Double> timePoints) {

    GaussianFit gs = new GaussianFit(shape_, fitMode_);

    double cPCF = photonConversionFactor_ / gain_;

    // for now, take the active ImageJ image
    // (this should be an image of a difraction limited spot)

    Roi originalRoi = siPlus.getRoi();
    if (null == originalRoi) {
      if (!silent_) IJ.error("Please draw a Roi around the spot you want to track");
      return false;
    }

    Polygon pol = FindLocalMaxima.FindMax(siPlus, halfSize_, noiseTolerance_, preFilterType_);
    if (pol.npoints == 0) {
      if (!silent_) ReportingUtils.showError("No local maxima found in ROI");
      else ReportingUtils.logError("No local maxima found in ROI");
      return false;
    }

    int xc = pol.xpoints[0];
    int yc = pol.ypoints[0];
    // not sure if needed, but look for the maximum local maximum
    int max = siPlus.getProcessor().getPixel(pol.xpoints[0], pol.ypoints[0]);
    if (pol.npoints > 1) {
      for (int i = 1; i < pol.npoints; i++) {
        if (siPlus.getProcessor().getPixel(pol.xpoints[i], pol.ypoints[i]) > max) {
          max = siPlus.getProcessor().getPixel(pol.xpoints[i], pol.ypoints[i]);
          xc = pol.xpoints[i];
          yc = pol.ypoints[i];
        }
      }
    }

    long startTime = System.nanoTime();

    // This is confusing.   We like to accomodate stacks with multiple slices
    // and stacks with multiple frames (which is actually the correct way

    int ch = siPlus.getChannel();
    Boolean useSlices = siPlus.getNSlices() > siPlus.getNFrames();

    int n = siPlus.getSlice();
    int nMax = siPlus.getNSlices();
    if (!useSlices) {
      n = siPlus.getFrame();
      nMax = siPlus.getNFrames();
    }
    boolean stop = false;
    int missedFrames = 0;
    int size = 2 * halfSize_;

    for (int i = n; i <= nMax && !stop; i++) {
      SpotData spot;

      // Give user feedback
      ij.IJ.showStatus("Tracking...");
      ij.IJ.showProgress(i, nMax);

      // Search in next slice in same Roi for local maximum
      Roi searchRoi = new Roi(xc - size, yc - size, 2 * size + 1, 2 * size + 1);
      if (useSlices) {
        siPlus.setSliceWithoutUpdate(siPlus.getStackIndex(ch, i, 1));
      } else {
        siPlus.setSliceWithoutUpdate(siPlus.getStackIndex(ch, 1, i));
      }
      siPlus.setRoi(searchRoi, false);

      // Find maximum in Roi, might not be needed....
      pol = FindLocalMaxima.FindMax(siPlus, 2 * halfSize_, noiseTolerance_, preFilterType_);

      // do not stray more than 2 pixels in x or y.
      // This velocity maximum parameter should be tunable by the user
      if (pol.npoints >= 1) {
        if (Math.abs(xc - pol.xpoints[0]) < 2 && Math.abs(yc - pol.ypoints[0]) < 2) {
          xc = pol.xpoints[0];
          yc = pol.ypoints[0];
        }
      }

      // Reset ROI to the original
      if (i == n) {
        firstX_ = xc;
        firstY_ = yc;
      }

      // Set Roi for fitting centered around maximum
      Roi spotRoi = new Roi(xc - halfSize_, yc - halfSize_, 2 * halfSize_, 2 * halfSize_);
      siPlus.setRoi(spotRoi, false);
      ImageProcessor ip;
      try {
        if (siPlus.getRoi() != spotRoi) {
          ReportingUtils.logError(
              "There seems to be a thread synchronization issue going on that causes this weirdness");
        }
        ip = siPlus.getProcessor().crop();
      } catch (ArrayIndexOutOfBoundsException aex) {
        ReportingUtils.logError(aex, "ImageJ failed to crop the image, not sure why");
        siPlus.setRoi(spotRoi, true);
        ip = siPlus.getProcessor().crop();
      }

      spot = new SpotData(ip, ch, 1, i, 1, i, xc, yc);
      double[] paramsOut = gs.dogaussianfit(ip, maxIterations_);
      double sx;
      double sy;
      double a = 1.0;
      double theta = 0.0;
      if (paramsOut.length >= 4) {
        // anormalize the intensity from the Gaussian fit
        double N =
            cPCF
                * paramsOut[GaussianFit.INT]
                * (2 * Math.PI * paramsOut[GaussianFit.S] * paramsOut[GaussianFit.S]);
        double xpc = paramsOut[GaussianFit.XC];
        double ypc = paramsOut[GaussianFit.YC];
        double x = (xpc - halfSize_ + xc) * pixelSize_;
        double y = (ypc - halfSize_ + yc) * pixelSize_;

        double s = paramsOut[GaussianFit.S] * pixelSize_;
        // express background in photons after base level correction
        double bgr = cPCF * (paramsOut[GaussianFit.BGR] - baseLevel_);
        // calculate error using formular from Thompson et al (2002)
        // (dx)2 = (s*s + (a*a/12)) / N + (8*pi*s*s*s*s * b*b) / (a*a*N*N)
        double sigma =
            (s * s + (pixelSize_ * pixelSize_) / 12) / N
                + (8 * Math.PI * s * s * s * s * bgr * bgr) / (pixelSize_ * pixelSize_ * N * N);
        sigma = Math.sqrt(sigma);

        double width = 2 * s;
        if (paramsOut.length >= 6) {
          sx = paramsOut[GaussianFit.S1] * pixelSize_;
          sy = paramsOut[GaussianFit.S2] * pixelSize_;
          a = sx / sy;
        }

        if (paramsOut.length >= 7) {
          theta = paramsOut[GaussianFit.S3];
        }
        if ((!useWidthFilter_ || (width > widthMin_ && width < widthMax_))
            && (!useNrPhotonsFilter_ || (N > nrPhotonsMin_ && N < nrPhotonsMax_))) {
          // If we have a good fit, update position of the box
          if (xpc > 0 && xpc < (2 * halfSize_) && ypc > 0 && ypc < (2 * halfSize_)) {
            xc += (int) xpc - halfSize_;
            yc += (int) ypc - halfSize_;
          }
          spot.setData(N, bgr, x, y, 0.0, 2 * s, a, theta, sigma);
          xyPoints.add(new Point2D.Double(x, y));
          timePoints.add(i * timeIntervalMs_);
          resultList_.add(spot);
          missedFrames = 0;
        } else {
          missedFrames += 1;
        }
      } else {
        missedFrames += 1;
      }
      if (endTrackAfterBadFrames_) {
        if (missedFrames >= this.endTrackAfterNBadFrames_) {
          stop = true;
        }
      }
    }

    long endTime = System.nanoTime();
    double took = (endTime - startTime) / 1E6;

    print("Calculation took: " + took + " milli seconds");

    ij.IJ.showStatus("");

    siPlus.setSlice(n);
    siPlus.setRoi(originalRoi);

    return true;
  }
Ejemplo n.º 10
0
 /**
  * LocalThicknesstoCleanedUpLocalThickness
  *
  * <p>Input: 3D Local Thickness map (32-bit stack)
  *
  * <p>Output: Same as input with border voxels corrected for "jaggies." Non-background voxels
  * adjacent to background voxels are have their local thickness values replaced by the average of
  * their non-background neighbors that do not border background points. Bob Dougherty August 1,
  * 2007
  *
  * <ul>
  *   <li>August 10. Version 3 This version also multiplies the local thickness by 2 to conform
  *       with the official definition of local thickness.
  * </ul>
  */
 private ImagePlus localThicknesstoCleanedUpLocalThickness(ImagePlus imp, float[][] s) {
   final int w = imp.getWidth();
   final int h = imp.getHeight();
   final int d = imp.getStackSize();
   IJ.showStatus("Cleaning up local thickness...");
   // Create 32 bit floating point stack for output, sNew.
   ImageStack newStack = new ImageStack(w, h);
   sNew = new float[d][];
   for (int k = 0; k < d; k++) {
     ImageProcessor ipk = new FloatProcessor(w, h);
     newStack.addSlice(null, ipk);
     sNew[k] = (float[]) ipk.getPixels();
   }
   /*
    * First set the output array to flags: 0 for a background point -1 for
    * a non-background point that borders a background point s (input data)
    * for an interior non-background point
    */
   for (int k = 0; k < d; k++) {
     for (int j = 0; j < h; j++) {
       final int wj = w * j;
       for (int i = 0; i < w; i++) {
         sNew[k][i + wj] = setFlag(s, i, j, k, w, h, d);
       } // i
     } // j
   } // k
   /*
    * Process the surface points. Initially set results to negative values
    * to be able to avoid including them in averages of for subsequent
    * points. During the calculation, positive values in sNew are interior
    * non-background local thicknesses. Negative values are surface points.
    * In this case the value might be -1 (not processed yet) or -result,
    * where result is the average of the neighboring interior points.
    * Negative values are excluded from the averaging.
    */
   for (int k = 0; k < d; k++) {
     for (int j = 0; j < h; j++) {
       final int wj = w * j;
       for (int i = 0; i < w; i++) {
         final int ind = i + wj;
         if (sNew[k][ind] == -1) {
           sNew[k][ind] = -averageInteriorNeighbors(s, i, j, k, w, h, d);
         }
       } // i
     } // j
   } // k
   // Fix the negative values and double the results
   for (int k = 0; k < d; k++) {
     for (int j = 0; j < h; j++) {
       final int wj = w * j;
       for (int i = 0; i < w; i++) {
         final int ind = i + wj;
         sNew[k][ind] = (float) Math.abs(sNew[k][ind]);
       } // i
     } // j
   } // k
   IJ.showStatus("Clean Up Local Thickness complete");
   String title = stripExtension(imp.getTitle());
   ImagePlus impOut = new ImagePlus(title + "_CL", newStack);
   final double vW = imp.getCalibration().pixelWidth;
   // calibrate the pixel values to pixel width
   // so that thicknesses represent real units (not pixels)
   for (int z = 0; z < d; z++) {
     impOut.setSlice(z + 1);
     impOut.getProcessor().multiply(vW);
   }
   return impOut;
 }
Ejemplo n.º 11
0
  public void run(String arg) {
    ImageCheck ic = new ImageCheck();
    if (!ImageCheck.checkEnvironment()) return;
    ImagePlus imp = IJ.getImage();
    if (!ic.isBinary(imp)) {
      IJ.error("8-bit binary (black and white only) image required.");
      return;
    }

    if (!ic.isVoxelIsotropic(imp, 1E-3)) {
      if (IJ.showMessageWithCancel(
          "Anisotropic voxels",
          "This image contains anisotropic voxels, which will\n"
              + "result in incorrect thickness calculation.\n\n"
              + "Consider rescaling your data so that voxels are isotropic\n"
              + "(Image > Scale...).\n\n"
              + "Continue anyway?")) {
      } else return;
    }
    GenericDialog gd = new GenericDialog("Options");
    gd.addCheckbox("Thickness", true);
    gd.addCheckbox("Spacing", false);
    gd.addCheckbox("Graphic Result", true);
    gd.addCheckbox("Use_ROI_Manager", false);
    gd.addCheckbox("Mask thickness map", true);
    gd.addHelp("http://bonej.org/thickness");
    gd.showDialog();
    if (gd.wasCanceled()) {
      return;
    }
    boolean doThickness = gd.getNextBoolean();
    boolean doSpacing = gd.getNextBoolean();
    boolean doGraphic = gd.getNextBoolean();
    boolean doRoi = gd.getNextBoolean();
    boolean doMask = gd.getNextBoolean();

    long startTime = System.currentTimeMillis();
    String title = stripExtension(imp.getTitle());

    RoiManager roiMan = RoiManager.getInstance();
    // calculate trabecular thickness (Tb.Th)
    if (doThickness) {
      boolean inverse = false;
      ImagePlus impLTC = new ImagePlus();
      if (doRoi && roiMan != null) {
        ImageStack stack = RoiMan.cropStack(roiMan, imp.getStack(), true, 0, 1);
        ImagePlus crop = new ImagePlus(imp.getTitle(), stack);
        crop.setCalibration(imp.getCalibration());
        impLTC = getLocalThickness(crop, inverse, doMask);
      } else impLTC = getLocalThickness(imp, inverse, doMask);
      impLTC.setTitle(title + "_Tb.Th");
      impLTC.setCalibration(imp.getCalibration());
      double[] stats = StackStats.meanStdDev(impLTC);
      insertResults(imp, stats, inverse);
      if (doGraphic && !Interpreter.isBatchMode()) {
        impLTC.show();
        impLTC.setSlice(1);
        impLTC.getProcessor().setMinAndMax(0, stats[2]);
        IJ.run("Fire");
      }
    }
    if (doSpacing) {
      boolean inverse = true;
      ImagePlus impLTCi = new ImagePlus();
      if (doRoi && roiMan != null) {
        ImageStack stack = RoiMan.cropStack(roiMan, imp.getStack(), true, 255, 1);
        ImagePlus crop = new ImagePlus(imp.getTitle(), stack);
        crop.setCalibration(imp.getCalibration());
        impLTCi = getLocalThickness(crop, inverse, doMask);
      } else impLTCi = getLocalThickness(imp, inverse, doMask);
      // check marrow cavity size (i.e. trabcular separation, Tb.Sp)
      impLTCi.setTitle(title + "_Tb.Sp");
      impLTCi.setCalibration(imp.getCalibration());
      double[] stats = StackStats.meanStdDev(impLTCi);
      insertResults(imp, stats, inverse);
      if (doGraphic && !Interpreter.isBatchMode()) {
        impLTCi.show();
        impLTCi.setSlice(1);
        impLTCi.getProcessor().setMinAndMax(0, stats[2]);
        IJ.run("Fire");
      }
    }
    IJ.showProgress(1.0);
    IJ.showStatus("Done");
    double duration = ((double) System.currentTimeMillis() - (double) startTime) / (double) 1000;
    IJ.log("Duration = " + IJ.d2s(duration, 3) + " s");
    UsageReporter.reportEvent(this).send();
    return;
  }
Ejemplo n.º 12
0
	public void run(String arg) {

  int[] wList = WindowManager.getIDList();
        if (wList==null) {
            IJ.error("No images are open.");
            return;
        }
	double kernel=3;
	double kernelsum = 0;
	double kernelvarsum =0;
	double kernalvar = 0;
	double sigmawidth = 2;
	int kernelindex, minpixnumber;
	String[] kernelsize =  { "3�,"5�, "7�, "9�};

	GenericDialog gd = new GenericDialog("Sigma Filter");
	gd.addChoice("Kernel size", kernelsize, kernelsize[0]);
	gd.addNumericField("Sigma width",sigmawidth , 2);
	gd.addNumericField("Minimum number of pixels", 1, 0);

	gd.addCheckbox("Keep source:",true);
	gd.addCheckbox("Do all stack:",true);
	gd.addCheckbox("Modified Lee's FIlter:",true);
	       	
	gd.showDialog();
       	if (gd.wasCanceled()) return ;
	kernelindex =  gd.getNextChoiceIndex();
          	sigmawidth = gd.getNextNumber();
          	minpixnumber = ((int)gd.getNextNumber());
          	boolean keep = gd.getNextBoolean();
	boolean doallstack = gd.getNextBoolean();
	boolean modified = gd.getNextBoolean();
	if (kernelindex==0) kernel = 3;
	if (kernelindex==1) kernel = 5;
	if (kernelindex==2) kernel = 7;
	if (kernelindex==3) kernel = 9;
    	long start = System.currentTimeMillis();
	
if (minpixnumber> (kernel*kernel)){
	      IJ.showMessage("Sigma filter", "There must be more pixels in the kernel than+\n" + "the minimum number to be included");
            return;
        }
	double v, midintensity;
	int   x, y, ix, iy;
	double sum = 0;
	double backupsum =0;
	int count = 0;
	int n = 0;
	if (keep) {IJ.run("Select All"); IJ.run("Duplicate...", "title='Sigma filtered' duplicate");}

	int radius = (int)(kernel-1)/2;
	ImagePlus imp = WindowManager.getCurrentImage();
	ImageStack stack1 = imp.getStack();
	int width = imp.getWidth();
	int height = imp.getHeight();
	int nslices = stack1.getSize();
	int cslice = imp.getCurrentSlice();
	double status = width*height*nslices;
	
	ImageProcessor  ip = imp.getProcessor();
	int sstart = 1;
	if (!doallstack) {sstart = cslice; nslices=sstart;status = status/nslices;};

 for (int i=sstart; i<=nslices; i++) {
                imp.setSlice(i);
                    
for (x=radius;x<width+radius;x++)	{
		for (y=radius;y<height+radius;y++)	{
			
			midintensity = ip.getPixelValue(x,y);
			count = 0;
			sum = 0;
			kernelsum =0;
			kernalvar =0;
			kernelvarsum =0;
			backupsum = 0;

		//calculate mean of kernel value
			for (ix=0;ix<kernel;ix++)	{
					for (iy=0;iy<kernel;iy++)	{
							v = ip.getPixelValue(x+ix-radius,y+iy-radius);
							kernelsum = kernelsum+v;
								}
						}
			double sigmacalcmean = (kernelsum/(kernel*kernel));

		//calculate variance of kernel
			for (ix=0;ix<kernel;ix++)	{
					for (iy=0;iy<kernel;iy++)	{
							v = ip.getPixelValue(x+ix-radius,y+iy-radius);
							kernalvar = (v-sigmacalcmean)*(v-sigmacalcmean);
							kernelvarsum = kernelvarsum + kernalvar;
								}
						}
			//double variance = kernelvarsum/kernel;
			double sigmacalcvar = kernelvarsum/((kernel*kernel)-1);

			//calcuate sigma range = sqrt(variance/(mean^2)) � sigmawidth
			double sigmarange  = sigmawidth*(Math.sqrt((sigmacalcvar) /(sigmacalcmean*sigmacalcmean)));
			//calulate sigma top value and bottom value
			double sigmatop = midintensity*(1+sigmarange);
			double sigmabottom = midintensity*(1-sigmarange);
			//calculate mean of values that differ are in sigma range.
			for (ix=0;ix<kernel;ix++)	{
					for (iy=0;iy<kernel;iy++)	{
							v = ip.getPixelValue(x+ix-radius,y+iy-radius);
							if ((v>=sigmabottom)&&(v<=sigmatop)){
								sum = sum+v;
								count = count+1;   }
								backupsum = v+ backupsum;
										}		
						}
//if there are too few pixels in the kernal that are within sigma range, the 
//mean of the entire kernal is taken. My modification of Lee's filter is to exclude the central value 
//from the calculation of the mean as I assume it to be spuriously high or low 
			if (!(count>(minpixnumber)))
				{sum = (backupsum-midintensity);
				count = (int)((kernel*kernel)-1);
				if (!modified)
					{sum = (backupsum);
					count  = (int)(kernel*kernel);}
				}
			
			double val =  (sum/count);
			ip.putPixelValue(x,y, val);
			n = n+1;
	double percentage = (((double)n/status)*100);
			 IJ.showStatus(IJ.d2s(percentage,0) +"% done");		
			
}

	//		IJ.showProgress(i, status);
					}}
			imp.updateAndDraw();
 			IJ.showStatus(IJ.d2s((System.currentTimeMillis()-start)/1000.0, 2)+" seconds");        }      
Ejemplo n.º 13
0
  /*------------------------------------------------------------------*/
  public void run(String arg) {
    ImagePlus imp = WindowManager.getCurrentImage();
    this.imp = imp;
    if (imp == null) {
      IJ.noImage();
      return;
    }
    if ((1 < imp.getStackSize()) && (imp.getType() == imp.COLOR_256)) {
      IJ.error("Stack of color images not supported (use grayscale)");
      return;
    }
    if (1 < imp.getStackSize()) {
      if (imp.getStack().isRGB()) {
        IJ.error("RGB color images not supported (use grayscale)");
        return;
      }
    }
    if (1 < imp.getStackSize()) {
      if (imp.getStack().isHSB()) {
        IJ.error("HSB color images not supported (use grayscale)");
        return;
      }
    }
    if (imp.getType() == imp.COLOR_256) {
      IJ.error("Indexed color images not supported (use grayscale)");
      return;
    }
    if (imp.getType() == imp.COLOR_RGB) {
      IJ.error("Color images not supported (use grayscale)");
      return;
    }

    differentialsDialog dialog =
        new differentialsDialog(IJ.getInstance(), "Differentials", true, operation);
    GUI.center(dialog);
    dialog.setVisible(true);
    cancel = dialog.getCancel();
    operation = dialog.getOperation();
    dialog.dispose();
    if (cancel) {
      return;
    }

    imp.startTiming();
    if (1 < imp.getStackSize()) {
      if (!(imp.getProcessor().getPixels() instanceof float[])) {
        new StackConverter(imp).convertToGray32();
      }
    } else {
      if (!(imp.getProcessor().getPixels() instanceof float[])) {
        new ImageConverter(imp).convertToGray32();
      }
    }
    ImageStack stack = imp.getStack();
    stackSize = stack.getSize();
    Undo.reset();

    setupProgressBar();
    resetProgressBar();

    for (int i = 1; (i <= stackSize); i++) {
      ImageProcessor ip = stack.getProcessor(i);
      doIt(ip);
      imp.getProcessor().resetMinAndMax();
      imp.setSlice(i);
      imp.updateAndRepaintWindow();
    }
    imp.getProcessor().resetMinAndMax();
    imp.setSlice(1);
    imp.updateAndRepaintWindow();
    cleanUpProgressBar();
    IJ.showTime(imp, imp.getStartTime(), "Differentials: ");
    ImageWindow win = imp.getWindow();
    if (win != null) {
      win.running = false;
    }
  } /* end run */
Ejemplo n.º 14
0
  static ImagePlus openNewFormat(String path, DataInputStream dis) throws IOException {
    // ImagePlus imp;
    // New version of VM using 12 parameter fields
    int version = reverse(dis.readInt());
    int type = reverse(dis.readInt());
    int size1 = reverse(dis.readInt());
    int size2 = reverse(dis.readInt());
    int size3 = reverse(dis.readInt());
    ImageStack stack = new ImageStack(size1, size2);

    int voxelUnit = reverse(dis.readInt());
    float voxelWidth = Float.intBitsToFloat(reverse(dis.readInt()));
    float voxelHeight = Float.intBitsToFloat(reverse(dis.readInt()));
    float voxelDepth = Float.intBitsToFloat(reverse(dis.readInt()));

    final int numPixels = size1 * size2;
    final int bufferSize = 4 * numPixels;

    final byte[] buffer = new byte[bufferSize];

    // write pixels
    for (int z = 0; z < size3; ++z) {

      final float[][] pixels = new float[size1][size2];

      int n = dis.read(buffer, 0, bufferSize);

      for (int j = 0; j < bufferSize; j += 4) {
        int tmp =
            (int)
                (((buffer[j + 3] & 0xff) << 24)
                    | ((buffer[j + 2] & 0xff) << 16)
                    | ((buffer[j + 1] & 0xff) << 8)
                    | (buffer[j] & 0xff));

        int currentPos = j / 4;
        int y = currentPos / size2;
        int x = currentPos % size2;

        if (type == 5) pixels[y][x] = Float.intBitsToFloat(tmp); // float type
        else if (type == 2) pixels[y][x] = (float) tmp; // int type
      }
      final FloatProcessor fp = new FloatProcessor(pixels);
      stack.addSlice(fp);
    }

    ImagePlus imp = new ImagePlus(path, stack);

    if (size3 > 1) {
      imp.setSlice(size3 / 2);
      ImageProcessor ip = imp.getProcessor();
      ip.resetMinAndMax();
      imp.setDisplayRange(ip.getMin(), ip.getMax());
    }

    Calibration calibration = new Calibration();
    String unit = intToUnitString(voxelUnit);
    calibration.setXUnit(unit);
    calibration.setYUnit(unit);
    calibration.setZUnit(unit);
    calibration.pixelWidth = voxelWidth;
    calibration.pixelHeight = voxelHeight;
    calibration.pixelDepth = voxelDepth;
    imp.setCalibration(calibration);

    return imp;
  }
Ejemplo n.º 15
0
  public boolean dialogItemChanged(GenericDialog gd, AWTEvent e) {
    if (IJ.isMacOSX()) IJ.wait(50);
    Calibration cal = imp.getCalibration();
    width = gd.getNextNumber();
    height = gd.getNextNumber();
    xRoi = gd.getNextNumber();
    yRoi = gd.getNextNumber();
    if (stackSize > 1) iSlice = (int) gd.getNextNumber();
    oval = gd.getNextBoolean();
    square = gd.getNextBoolean();
    centered = gd.getNextBoolean();
    if (cal.scaled()) scaledUnits = gd.getNextBoolean();
    if (gd.invalidNumber() || width <= 0 || height <= 0) return false;
    //
    Vector numFields = gd.getNumericFields();
    Vector checkboxes = gd.getCheckboxes();
    boolean newWidth = false, newHeight = false, newXY = false;
    if (e != null && e.getSource() == checkboxes.get(SQUARE) && square) {
      width = 0.5 * (width + height); // make square: same width&height
      height = width;
      newWidth = true;
      newHeight = true;
    }
    if (e != null && e.getSource() == checkboxes.get(CENTERED)) {
      double shiftBy = centered ? 0.5 : -0.5; // 'centered' changed:
      xRoi += shiftBy * width; // shift x, y to keep roi the same
      yRoi += shiftBy * height;
      newXY = true;
    }
    if (square && width != height && e != null) { // in 'square' mode, synchronize width&height
      if (e.getSource() == numFields.get(WIDTH)) {
        height = width;
        newHeight = true;
      } else if (e.getSource() == numFields.get(HEIGHT)) {
        width = height;
        newWidth = true;
      }
    }
    if (e != null && cal.scaled() && e.getSource() == checkboxes.get(SCALED_UNITS)) {
      double xFactor = scaledUnits ? cal.pixelWidth : 1. / cal.pixelWidth;
      double yFactor = scaledUnits ? cal.pixelHeight : 1. / cal.pixelHeight;
      width *= xFactor; // transform everything to keep roi the same
      height *= yFactor;
      xRoi *= xFactor;
      yRoi *= yFactor;
      newWidth = true;
      newHeight = true;
      newXY = true;
    }
    int digits = (scaledUnits || (int) width != width) ? 2 : 0;
    if (newWidth) ((TextField) (numFields.get(WIDTH))).setText(IJ.d2s(width, digits));
    if (newHeight) ((TextField) (numFields.get(HEIGHT))).setText(IJ.d2s(height, digits));
    digits = (scaledUnits || (int) xRoi != xRoi || (int) yRoi != yRoi) ? 2 : 0;
    if (newXY) {
      ((TextField) (numFields.get(X_ROI))).setText(IJ.d2s(xRoi, digits));
      ((TextField) (numFields.get(Y_ROI))).setText(IJ.d2s(yRoi, digits));
    }

    if (stackSize > 1 && iSlice > 0 && iSlice <= stackSize) imp.setSlice(iSlice);
    if (!newWidth && !newHeight && !newXY) // don't draw if an update will come immediately
    drawRoi();
    return true;
  }
Ejemplo n.º 16
0
  /** Ask for parameters and then execute. */
  public void run(String arg) {
    // 1 - Obtain the currently active image:
    ImagePlus imp = IJ.getImage();

    if (null == imp) {
      IJ.showMessage("There must be at least one image open");
      return;
    }

    if (imp.getBitDepth() != 8) {
      IJ.showMessage("Error", "Only 8-bit images are supported");
      return;
    }

    // 2 - Ask for parameters:
    GenericDialog gd = new GenericDialog("Auto Local Threshold");
    String[] methods = {
      "Try all",
      "Bernsen",
      "Contrast",
      "Mean",
      "Median",
      "MidGrey",
      "Niblack",
      "Otsu",
      "Phansalkar",
      "Sauvola"
    };
    gd.addMessage("Auto Local Threshold v1.5");
    gd.addChoice("Method", methods, methods[0]);
    gd.addNumericField("Radius", 15, 0);
    gd.addMessage("Special paramters (if different from default)");
    gd.addNumericField("Parameter_1", 0, 0);
    gd.addNumericField("Parameter_2", 0, 0);
    gd.addCheckbox("White objects on black background", true);
    if (imp.getStackSize() > 1) {
      gd.addCheckbox("Stack", false);
    }
    gd.addMessage("Thresholded result is always shown in white [255].");
    gd.showDialog();
    if (gd.wasCanceled()) return;

    // 3 - Retrieve parameters from the dialog
    String myMethod = gd.getNextChoice();
    int radius = (int) gd.getNextNumber();
    double par1 = (double) gd.getNextNumber();
    double par2 = (double) gd.getNextNumber();
    boolean doIwhite = gd.getNextBoolean();
    boolean doIstack = false;

    int stackSize = imp.getStackSize();
    if (stackSize > 1) doIstack = gd.getNextBoolean();

    // 4 - Execute!
    // long start = System.currentTimeMillis();
    if (myMethod.equals("Try all")) {
      ImageProcessor ip = imp.getProcessor();
      int xe = ip.getWidth();
      int ye = ip.getHeight();
      int ml = methods.length;
      ImagePlus imp2, imp3;
      ImageStack tstack = null, stackNew;
      if (stackSize > 1 && doIstack) {
        boolean doItAnyway = true;
        if (stackSize > 25) {
          YesNoCancelDialog d =
              new YesNoCancelDialog(
                  IJ.getInstance(),
                  "Auto Local Threshold",
                  "You might run out of memory.\n \nDisplay "
                      + stackSize
                      + " slices?\n \n \'No\' will process without display and\noutput results to the log window.");
          if (!d.yesPressed()) {
            //						doIlog=true; //will show in the log window
            doItAnyway = false;
          }
          if (d.cancelPressed()) return;
        }

        for (int j = 1; j <= stackSize; j++) {
          imp.setSlice(j);
          ip = imp.getProcessor();
          tstack = new ImageStack(xe, ye);
          for (int k = 1; k < ml; k++) tstack.addSlice(methods[k], ip.duplicate());
          imp2 = new ImagePlus("Auto Threshold", tstack);
          imp2.updateAndDraw();

          for (int k = 1; k < ml; k++) {
            imp2.setSlice(k);
            Object[] result = exec(imp2, methods[k], radius, par1, par2, doIwhite);
          }
          // if (doItAnyway){
          CanvasResizer cr = new CanvasResizer();
          stackNew = cr.expandStack(tstack, (xe + 2), (ye + 18), 1, 1);
          imp3 = new ImagePlus("Auto Threshold", stackNew);
          imp3.updateAndDraw();
          MontageMaker mm = new MontageMaker();
          mm.makeMontage(imp3, 3, 3, 1.0, 1, (ml - 1), 1, 0, true); // 3 columns and 3 rows
        }
        imp.setSlice(1);
        // if (doItAnyway)
        IJ.run("Images to Stack", "method=[Copy (center)] title=Montage");
        return;
      } else { // single image try all
        tstack = new ImageStack(xe, ye);
        for (int k = 1; k < ml; k++) tstack.addSlice(methods[k], ip.duplicate());
        imp2 = new ImagePlus("Auto Threshold", tstack);
        imp2.updateAndDraw();

        for (int k = 1; k < ml; k++) {
          imp2.setSlice(k);
          // IJ.log("analyzing slice with "+methods[k]);
          Object[] result = exec(imp2, methods[k], radius, par1, par2, doIwhite);
        }
        // imp2.setSlice(1);
        CanvasResizer cr = new CanvasResizer();
        stackNew = cr.expandStack(tstack, (xe + 2), (ye + 18), 1, 1);
        imp3 = new ImagePlus("Auto Threshold", stackNew);
        imp3.updateAndDraw();
        MontageMaker mm = new MontageMaker();
        mm.makeMontage(imp3, 3, 3, 1.0, 1, (ml - 1), 1, 0, true);
        return;
      }
    } else { // selected a method
      if (stackSize > 1 && doIstack) { // whole stack
        //				if (doIstackHistogram) {// one global histogram
        //					Object[] result = exec(imp, myMethod, noWhite, noBlack, doIwhite, doIset, doIlog,
        // doIstackHistogram );
        //				}
        //				else{ // slice by slice
        for (int k = 1; k <= stackSize; k++) {
          imp.setSlice(k);
          Object[] result = exec(imp, myMethod, radius, par1, par2, doIwhite);
        }
        //				}
        imp.setSlice(1);
      } else { // just one slice
        Object[] result = exec(imp, myMethod, radius, par1, par2, doIwhite);
      }
      // 5 - If all went well, show the image:
      // not needed here as the source image is binarised
    }
  }
Ejemplo n.º 17
0
  public void Calc_5Fr(ImagePlus imp1, ImagePlus imp2) {
    if (imp1.getType() != imp2.getType()) {
      error();
      return;
    }
    if (imp1.getType() == 0) { // getType returns 0 for 8-bit, 1 for 16-bit
      bitDepth = "8-bit";
      Prefs.set("ps.bitDepth", bitDepth);
    } else {
      bitDepth = "16-bit";
      Prefs.set("ps.bitDepth", bitDepth);
    }
    int width = imp1.getWidth();
    int height = imp1.getHeight();
    if (width != imp2.getWidth() || height != imp2.getHeight()) {
      error();
      return;
    }

    ImageStack stack1 = imp1.getStack();
    //		if (bgStackTitle != "NoBg") ImageStack stack2 = imp2.getStack();
    ImageStack stack2 = imp2.getStack();

    ImageProcessor ip = imp1.getProcessor();
    int dimension = width * height;
    byte[] pixB;
    short[] pixS;
    float[][] pixF = new float[5][dimension];
    float[][] pixFBg = new float[5][dimension];

    float a;
    float b;
    float den;
    float aSmp;
    float bSmp;
    float denSmp;
    float aBg;
    float bBg;
    float denBg;
    float retF;
    float azimF;

    byte[] retB = new byte[dimension];
    short[] retS = new short[dimension];
    byte[] azimB = new byte[dimension];
    short[] azimS = new short[dimension];
    // Derived Variables:
    float swingAngle = 2f * (float) Math.PI * swing;
    float tanSwingAngleDiv2 = (float) Math.tan(swingAngle / 2.f);
    float tanSwingAngleDiv2DivSqrt2 = (float) (Math.tan(swingAngle / 2.f) / Math.sqrt(2));
    float wavelengthDiv2Pi = wavelength / (2f * (float) Math.PI);

    // get the pixels of each slice in the stack and convert to float
    for (int i = 0; i < 5; i++) {
      if (bitDepth == "8-bit") {
        pixB = (byte[]) stack1.getPixels(i + 3);
        for (int j = 0; j < dimension; j++) pixF[i][j] = 0xff & pixB[j];
        if (bgStackTitle != "NoBg") {
          pixB = (byte[]) stack2.getPixels(i + 3);
          for (int j = 0; j < dimension; j++) pixFBg[i][j] = 0xff & pixB[j];
        }
      } else {
        pixS = (short[]) stack1.getPixels(i + 3);
        for (int j = 0; j < dimension; j++) pixF[i][j] = (float) pixS[j];
        if (bgStackTitle != "NoBg") {
          pixS = (short[]) stack2.getPixels(i + 3);
          for (int j = 0; j < dimension; j++) pixFBg[i][j] = (float) pixS[j];
        }
      }
    }

    // Algorithm
    // terms a and b
    for (int j = 0; j < dimension; j++) {
      denSmp = (pixF[1][j] + pixF[2][j] + pixF[3][j] + pixF[4][j] - 4 * pixF[0][j]) / 2;
      denBg = denSmp;
      a = (pixF[4][j] - pixF[1][j]);
      aSmp = a;
      aBg = a;
      b = (pixF[2][j] - pixF[3][j]);
      bSmp = b;
      bBg = b;
      if (bgStackTitle != "NoBg") {
        denBg = (pixFBg[1][j] + pixFBg[2][j] + pixFBg[3][j] + pixFBg[4][j] - 4 * pixFBg[0][j]) / 2;
        aBg = pixFBg[4][j] - pixFBg[1][j];
        bBg = pixFBg[2][j] - pixFBg[3][j];
      }
      // Special case of sample retardance half wave, denSmp = 0
      if (denSmp == 0) {
        retF = (float) wavelength / 4;
        azimF =
            (float) (a == 0 & b == 0 ? 0 : (azimRef + 90 + 90 * Math.atan2(a, b) / Math.PI) % 180);
      } else {
        // Retardance, the background correction can be improved by separately considering sample
        // retardance values larger than a quarter wave
        if (bgStackTitle != "NoBg") {
          a = aSmp / denSmp - aBg / denBg;
          b = bSmp / denSmp - bBg / denBg;
        } else {
          a = aSmp / denSmp;
          b = bSmp / denSmp;
        }
        retF = (float) Math.atan(tanSwingAngleDiv2 * Math.sqrt(a * a + b * b));
        if (denSmp < 0) retF = (float) Math.PI - retF;
        retF = retF * wavelengthDiv2Pi; // convert to nm
        if (retF > retCeiling) retF = retCeiling;

        // Orientation
        if ((bgStackTitle == "NoBg") || ((bgStackTitle != "NoBg") && (Math.abs(denSmp) < 1))) {
          a = aSmp;
          b = bSmp;
        }
        azimF =
            (float) (a == 0 & b == 0 ? 0 : (azimRef + 90 + 90 * Math.atan2(a, b) / Math.PI) % 180);
      }
      if (bitDepth == "8-bit") retB[j] = (byte) (((int) (255 * retF / retCeiling)) & 0xff);
      else retS[j] = (short) (4095 * retF / retCeiling);
      if (mirror == "Yes") azimF = 180 - azimF;
      if (bitDepth == "8-bit") azimB[j] = (byte) (((int) azimF) & 0xff);
      else azimS[j] = (short) (azimF * 10f);
    }
    // show the resulting images in slice 1 and 2
    imp1.setSlice(3);
    if (bitDepth == "8-bit") {
      stack1.setPixels(retB, 1);
      stack1.setPixels(azimB, 2);
    } else {
      stack1.setPixels(retS, 1);
      stack1.setPixels(azimS, 2);
    }
    imp1.setSlice(1);
    IJ.selectWindow(imp1.getTitle());

    Prefs.set("ps.sampleStackTitle", sampleStackTitle);
    Prefs.set("ps.bgStackTitle", bgStackTitle);
    Prefs.set("ps.mirror", mirror);
    Prefs.set("ps.wavelength", wavelength);
    Prefs.set("ps.swing", swing);
    Prefs.set("ps.retCeiling", retCeiling);
    Prefs.set("ps.azimRef", azimRef);
    Prefs.savePreferences();
  }