@Override
  @SuppressWarnings("unchecked")
  public O calculate(final I kernel, final Dimensions paddedDimensions) {

    Dimensions paddedFFTInputDimensions;

    // if an fftsize op has been set recompute padded size
    if (fftSizeOp != null) {
      long[][] sizes = fftSizeOp.calculate(paddedDimensions);

      paddedFFTInputDimensions = new FinalDimensions(sizes[0]);
    } else {
      paddedFFTInputDimensions = paddedDimensions;
    }

    // compute where to place the final Interval for the kernel so that the
    // coordinate in the center
    // of the kernel is shifted to position (0,0).

    final Interval kernelConvolutionInterval =
        paddingIntervalCentered.calculate(kernel, paddedFFTInputDimensions);

    final Interval kernelConvolutionIntervalOrigin =
        paddingIntervalOrigin.calculate(kernel, kernelConvolutionInterval);

    return (O)
        Views.interval(
            Views.extendPeriodic(
                Views.interval(
                    Views.extendValue(kernel, Util.getTypeFromInterval(kernel).createVariable()),
                    kernelConvolutionInterval)),
            kernelConvolutionIntervalOrigin);
  }
Beispiel #2
0
  @Test
  public void testRandomAccessibleView() {
    @SuppressWarnings("unchecked")
    final RandomAccessible<ByteType> res =
        (RandomAccessible<ByteType>)
            ops.run(MapViewRandomAccessToRandomAccess.class, in, op, new ByteType());

    final Cursor<ByteType> iterable = Views.iterable(Views.interval(res, in)).cursor();
    while (iterable.hasNext()) {
      assertEquals((byte) 10, iterable.next().get());
    }
  }
 public static <T extends Type<T> & Comparable<T>> int countLocalMaxima(
     final RandomAccessibleInterval<T> img, final Shape shape) {
   int nMaxima = 0;
   final RandomAccessibleInterval<T> source = Views.interval(img, Intervals.expand(img, -1));
   final Cursor<T> center = Views.iterable(source).cursor();
   A:
   for (final Neighborhood<T> neighborhood : shape.neighborhoods(source)) {
     final T c = center.next();
     for (final T t : neighborhood) if (t.compareTo(c) > 0) continue A;
     ++nMaxima;
   }
   return nMaxima;
 }
Beispiel #4
0
  @SuppressWarnings("unchecked")
  @Override
  public boolean process() {
    final long start = System.currentTimeMillis();

    final ArrayImgFactory<FloatType> factory = new ArrayImgFactory<FloatType>();
    final ArrayImg<FloatType, FloatArray> floatImage =
        (ArrayImg<FloatType, FloatArray>) factory.create(source, new FloatType());

    // Copy to float.
    final Cursor<FloatType> cursor = floatImage.cursor(source);
    final RandomAccess<T> ra = source.randomAccess(source);
    while (cursor.hasNext()) {
      cursor.fwd();
      ra.setPosition(cursor);
      cursor.get().set(ra.get().getRealFloat());
    }

    // Create result holders.
    Dx = (ArrayImg<FloatType, FloatArray>) factory.create(source, new FloatType());
    Dy = (ArrayImg<FloatType, FloatArray>) factory.create(source, new FloatType());

    final int ndims = floatImage.numDimensions();
    if (ndims == 3) {
      final long nz = floatImage.dimension(2);
      for (int z = 0; z < nz; z++) {
        final IntervalView<FloatType> slice = Views.hyperSlice(floatImage, 2, z);
        final IntervalView<FloatType> targetSliceX = Views.hyperSlice(Dx, 2, z);
        final IntervalView<FloatType> targetSliceY = Views.hyperSlice(Dy, 2, z);
        final boolean ok = processSlice(slice, targetSliceX, targetSliceY);
        if (!ok) {
          return false;
        }
      }
    } else {
      final boolean ok = processSlice(floatImage, Dx, Dy);
      if (!ok) {
        return false;
      }
    }

    components.clear();
    components.add(Dx);
    components.add(Dy);

    final long end = System.currentTimeMillis();
    processingTime = end - start;
    return true;
  }
Beispiel #5
0
  /**
   * Computes a Gaussian convolution with double precision on an entire {@link Img}
   *
   * @param sigma - the sigma for the convolution
   * @param img - the img {@link Img}
   * @param outofbounds - the {@link OutOfBoundsFactory}
   * @return the convolved img in {@link DoubleType}
   */
  public static <T extends RealType<T>> Img<DoubleType> toDouble(
      final double[] sigma,
      final Img<T> img,
      final OutOfBoundsFactory<DoubleType, RandomAccessibleInterval<DoubleType>> outofbounds) {
    GaussDouble gauss = null;
    try {
      if (DoubleType.class.isInstance(img.firstElement())) {
        @SuppressWarnings({"rawtypes", "unchecked"})
        final Img<DoubleType> img2 = (Img) img;
        gauss = new GaussDouble(sigma, img2);
      } else {
        final RandomAccessibleInterval<DoubleType> rIn =
            new WriteConvertedIterableRandomAccessibleInterval<T, DoubleType, Img<T>>(
                img, new RealDoubleSamplerConverter<T>());
        gauss =
            new GaussDouble(
                sigma,
                Views.extend(rIn, outofbounds),
                img,
                img.factory().imgFactory(new DoubleType()));
      }
    } catch (final IncompatibleTypeException e) {
      return null;
    }

    gauss.call();

    return (Img<DoubleType>) gauss.getResult();
  }
Beispiel #6
0
  /**
   * Computes a Gaussian convolution with double precision on an entire {@link Img}
   *
   * @param sigma - the sigma for the convolution
   * @param img - the img {@link Img}
   * @param outofbounds - the {@link OutOfBoundsFactory}
   * @return the convolved img having the input type
   */
  @SuppressWarnings({"unchecked", "rawtypes"})
  public static <T extends RealType<T>> Img<T> inDouble(
      final double[] sigma,
      final Img<T> img,
      final OutOfBoundsFactory<DoubleType, RandomAccessibleInterval<DoubleType>> outofbounds) {
    try {
      if (DoubleType.class.isInstance(img.firstElement())) {
        return (Img) toDouble(sigma, img, outofbounds);
      }
      final Img<T> output = img.factory().create(img, img.firstElement());

      final RandomAccessible<DoubleType> rIn =
          Views.extend(
              new WriteConvertedRandomAccessibleInterval<T, DoubleType>(
                  img, new RealDoubleSamplerConverter<T>()),
              outofbounds);
      final RandomAccessible<DoubleType> rOut =
          new WriteConvertedRandomAccessible<T, DoubleType>(
              output, new RealDoubleSamplerConverter<T>());

      inDouble(
          sigma,
          rIn,
          img,
          rOut,
          new Point(sigma.length),
          img.factory().imgFactory(new DoubleType()));

      return output;
    } catch (final IncompatibleTypeException e) {
      return null;
    }
  }
Beispiel #7
0
 /**
  * Computes a Gaussian convolution in-place (temporary imgs are necessary) with the precision of
  * the type provided on an entire {@link Img}
  *
  * @param sigma - the sigma for the convolution
  * @param img - the img {@link Img} that will be convolved in place
  */
 public static <T extends NumericType<T>> void inNumericTypeInPlace(
     final double[] sigma,
     final Img<T> img,
     final OutOfBoundsFactory<T, RandomAccessibleInterval<T>> outofbounds) {
   inNumericType(
       sigma, Views.extend(img, outofbounds), img, img, new Point(sigma.length), img.factory());
 }
 @Override
 protected IterableIntervalProjector2D<T, ARGBType> getProjector(
     final int dimX,
     final int dimY,
     final RandomAccessibleInterval<T> source,
     final RandomAccessibleInterval<ARGBType> target) {
   return new IterableIntervalProjector2D<T, ARGBType>(
       dimX, dimY, source, Views.iterable(target), m_converter);
 }
 /**
  * Walk through an Interval on an Img using a Cursor
  *
  * @param img
  * @param interval
  */
 protected static void walkThrough(final Img<IntType> img, final Interval interval) {
   final Cursor<IntType> c = Views.interval(img, interval).cursor();
   int i = 0;
   while (c.hasNext()) {
     c.fwd();
     i += c.get().get();
   }
   j = i;
 }
Beispiel #10
0
 /**
  * Computes a Gaussian convolution with the precision of the type provided on an entire {@link
  * Img}
  *
  * @param sigma - the sigma for the convolution
  * @param img - the img {@link Img}
  * @param outofbounds - the {@link OutOfBoundsFactory}
  * @return the convolved img
  */
 public static <T extends NumericType<T>> Img<T> inNumericType(
     final double[] sigma,
     final Img<T> img,
     final OutOfBoundsFactory<T, RandomAccessibleInterval<T>> outofbounds) {
   final Img<T> output = img.factory().create(img, img.firstElement());
   inNumericType(
       sigma, Views.extend(img, outofbounds), img, output, new Point(sigma.length), img.factory());
   return output;
 }
  public FirstIteration(
      final ImagePortion portion,
      final RandomAccessibleInterval<FloatType> psi,
      final ArrayList<RandomAccessibleInterval<FloatType>> imgs,
      final ArrayList<RandomAccessibleInterval<FloatType>> weights) {
    this.portion = portion;
    this.psi = psi;
    this.imgs = imgs;
    this.weights = weights;

    this.psiIterable = Views.iterable(psi);
    this.iterableImgs = new ArrayList<IterableInterval<FloatType>>();
    this.iterableWeights = new ArrayList<IterableInterval<FloatType>>();

    this.realSum = new RealSum();

    if (imgs.size() != weights.size())
      throw new RuntimeException("Number of weights and images must be equal.");

    compatibleIteration = true;

    for (final RandomAccessibleInterval<FloatType> img : imgs) {
      final IterableInterval<FloatType> imgIterable = Views.iterable(img);

      if (!psiIterable.iterationOrder().equals(imgIterable.iterationOrder()))
        compatibleIteration = false;

      this.iterableImgs.add(imgIterable);
    }

    for (final RandomAccessibleInterval<FloatType> weight : weights) {
      final IterableInterval<FloatType> weightIterable = Views.iterable(weight);

      if (!psiIterable.iterationOrder().equals(weightIterable.iterationOrder()))
        compatibleIteration = false;

      for (final IterableInterval<FloatType> imgIterable : iterableImgs)
        if (!imgIterable.iterationOrder().equals(weightIterable.iterationOrder()))
          compatibleIteration = false;

      this.iterableWeights.add(weightIterable);
    }
  }
 /**
  * Compute the steepest descent images of the template at the identity warp. Each steepest descent
  * image comprises the partial derivatives of template intensities with respect to one parameter
  * of the warp function.
  *
  * <p>The result is stored in the <em>n+1</em> dimensional {@link #target} image. Dimension
  * <em>n</em> is used to index the partial derivative. For example, the partial derivative by the
  * second parameter of the warp function is stored in slice <em>n=1</em>.
  *
  * @param gradients n+1 dimensional image of partial derivatives of the template. Dimension n is
  *     used to index the partial derivative. For example, the partial derivative by Y is stored in
  *     slice n=1.
  * @param warpFunction The warp function to be applied to the template. The partial derivatives of
  *     template intensities with respect to the parameters of this warp function are computed.
  * @param target Image of <em>n+1</em> dimensions to store the steepest descent Dimension
  *     <em>n</em> is used to index the parameters of the warp function. For example, the partial
  *     derivative of the template image intensity by parameter 2 of the warp function at pixel
  *     <em>(x,y)</em> is stored at position <em>(x,y,1)</em>.
  */
 public static <T extends NumericType<T>> void computeSteepestDescents(
     final RandomAccessibleInterval<T> gradients,
     final WarpFunction warpFunction,
     final RandomAccessibleInterval<T> target) {
   final int n = gradients.numDimensions() - 1;
   final int numParameters = warpFunction.numParameters();
   final T tmp = Util.getTypeFromInterval(gradients).createVariable();
   for (int p = 0; p < numParameters; ++p) {
     for (int d = 0; d < n; ++d) {
       final Cursor<T> gd =
           Views.flatIterable(Views.hyperSlice(gradients, n, d)).localizingCursor();
       for (final T t : Views.flatIterable(Views.hyperSlice(target, n, p))) {
         tmp.set(gd.next());
         tmp.mul(warpFunction.partial(gd, d, p));
         t.add(tmp);
       }
     }
   }
 }
Beispiel #13
0
 @Override
 public RandomAccessibleInterval<T> compute(
     final RandomAccessibleInterval<T> input, final RandomAccessibleInterval<T> output) {
   final StructuringElementCursor<T> inStructure =
       new StructuringElementCursor<T>(Views.extend(input, m_factory).randomAccess(), m_struc);
   final Cursor<T> out = Views.iterable(output).localizingCursor();
   double m;
   while (out.hasNext()) {
     out.next();
     inStructure.relocate(out);
     inStructure.next();
     m = inStructure.get().getRealDouble();
     while (inStructure.hasNext()) {
       inStructure.next();
       m = Math.min(m, inStructure.get().getRealDouble());
     }
     out.get().setReal(m);
   }
   return output;
 }
  double alignStep(final RandomAccessibleInterval<T> image) {
    // compute error image = warped image - template
    computeDifference(Views.extendBorder(image), currentTransform, template, error);

    // compute transform parameter update
    final double[] gradient = new double[numParameters];
    for (int p = 0; p < numParameters; ++p) {
      final Cursor<T> err = Views.flatIterable(error).cursor();
      for (final T t : Views.flatIterable(Views.hyperSlice(descent, n, p)))
        gradient[p] += t.getRealDouble() * err.next().getRealDouble();
    }
    final double[] dp = new double[numParameters];
    LinAlgHelpers.mult(Hinv, gradient, dp);

    // udpate transform
    currentTransform.preConcatenate(warpFunction.getAffine(dp));

    // return norm of parameter update vector
    return LinAlgHelpers.length(dp);
  }
  @Test
  public void defaultCollapseNumericTest() {

    Img<NativeARGBDoubleType> img =
        new ArrayImgFactory<NativeARGBDoubleType>()
            .create(new int[] {10, 10}, new NativeARGBDoubleType());

    CompositeIntervalView<NativeARGBDoubleType, NumericComposite<NativeARGBDoubleType>> il2 =
        Views.collapseNumeric((RandomAccessibleInterval<NativeARGBDoubleType>) img);
    CompositeIntervalView<NativeARGBDoubleType, NumericComposite<NativeARGBDoubleType>> opr =
        ops.transform().collapseNumeric((RandomAccessibleInterval<NativeARGBDoubleType>) img);

    assertEquals(il2.numDimensions(), opr.numDimensions());

    CompositeView<NativeARGBDoubleType, NumericComposite<NativeARGBDoubleType>> il2_2 =
        Views.collapseNumeric((RandomAccessible<NativeARGBDoubleType>) img, 1);
    CompositeView<NativeARGBDoubleType, NumericComposite<NativeARGBDoubleType>> opr_2 =
        ops.transform().collapseNumeric((RandomAccessible<NativeARGBDoubleType>) img, 1);

    assertEquals(il2_2.numDimensions(), opr_2.numDimensions());
  }
Beispiel #16
0
  /**
   * Extends the given {@link ImgPlus} to 5-dimensions and makes sure, that the dimension order
   * suits IJ.
   *
   * @param img to be extended and permuted
   * @return extended and permuted {@link Img}
   */
  public static <T> RandomAccessibleInterval<T> extendAndPermute(final ImgPlus<T> img) {

    // Create Mapping [at position one -> new index, at position 2 -> new index etc.] given: ImgPlus
    // and m_mapping
    // we always want to have 5 dimensions
    RandomAccessibleInterval<T> extended = img;
    for (int d = img.numDimensions(); d < 5; d++) {
      extended = Views.addDimension(extended, 0, 0);
    }

    return DimSwapper.swap(extended, getInferredMapping(img));
  }
Beispiel #17
0
 @Override
 public void run() {
   double[] sigmas = sigmas();
   @SuppressWarnings("unchecked")
   Img<T> target = (Img<T>) dataset.getImgPlus();
   Img<T> input = target.copy();
   ExtendedRandomAccessibleInterval<T, ?> paddedInput = Views.extendMirrorSingle(input);
   try {
     Gauss3.gauss(sigmas, paddedInput, target);
   } catch (Exception e) {
     cancel(e.getMessage());
   }
 }
  /**
   * Walk through an Interval on an Img using a LocalizingCursor, localizing on every step.
   *
   * @param img
   * @param interval
   */
  protected static void localizingWalkThrough(final Img<IntType> img, final Interval interval) {
    final Cursor<IntType> c = Views.interval(img, interval).localizingCursor();

    final long[] pos = new long[interval.numDimensions()];

    int i = 0;
    while (c.hasNext()) {
      c.fwd();
      i += c.get().get();
      c.localize(pos);
    }
    j = (int) pos[0] + i;
  }
Beispiel #19
0
  private Img<?> getUsableImage(final Img<ComplexType<?>> img) {
    if (m_imgBuffer.size() > 0) {
      return m_imgBuffer.poll();
    } else {
      Img tmpImg = m_imgFactory.create(img, m_resultType);

      // wrap the result image with an ImgView in case the other image has an offset (i.e. minimum)
      // -> if not set, an iteration order exception will occur
      long[] min = new long[img.numDimensions()];
      img.min(min);
      return ImgView.wrap(Views.translate(tmpImg, min), tmpImg.factory());
    }
  }
Beispiel #20
0
 public static final <T extends RealType<T>> void addGaussianNoiseToImage(
     RandomAccessibleInterval<T> img, double sigma_noise) {
   IterableInterval<T> iterImg = Views.iterable(img);
   Cursor<T> lc = iterImg.localizingCursor();
   double val;
   T var = iterImg.firstElement().createVariable();
   while (lc.hasNext()) {
     lc.fwd();
     val = Math.max(0, sigma_noise * ran.nextGaussian());
     var.setReal(val);
     lc.get().add(var);
   }
 }
  /**
   * TODO
   *
   * @param cumulativeMinCutoff
   * @param cumulativeMaxCutoff
   * @param state
   * @param setupAssignments
   */
  public static void initBrightness(
      final double cumulativeMinCutoff,
      final double cumulativeMaxCutoff,
      final ViewerState state,
      final SetupAssignments setupAssignments) {
    final Source<?> source = state.getSources().get(state.getCurrentSource()).getSpimSource();
    final int timepoint = state.getCurrentTimepoint();
    if (!source.isPresent(timepoint)) return;
    if (!UnsignedShortType.class.isInstance(source.getType())) return;
    @SuppressWarnings("unchecked")
    final RandomAccessibleInterval<UnsignedShortType> img =
        (RandomAccessibleInterval<UnsignedShortType>)
            source.getSource(timepoint, source.getNumMipmapLevels() - 1);
    final long z = (img.min(2) + img.max(2) + 1) / 2;

    final int numBins = 6535;
    final Histogram1d<UnsignedShortType> histogram =
        new Histogram1d<UnsignedShortType>(
            Views.iterable(Views.hyperSlice(img, 2, z)),
            new Real1dBinMapper<UnsignedShortType>(0, 65535, numBins, false));
    final DiscreteFrequencyDistribution dfd = histogram.dfd();
    final long[] bin = new long[] {0};
    double cumulative = 0;
    int i = 0;
    for (; i < numBins && cumulative < cumulativeMinCutoff; ++i) {
      bin[0] = i;
      cumulative += dfd.relativeFrequency(bin);
    }
    final int min = i * 65535 / numBins;
    for (; i < numBins && cumulative < cumulativeMaxCutoff; ++i) {
      bin[0] = i;
      cumulative += dfd.relativeFrequency(bin);
    }
    final int max = i * 65535 / numBins;
    final MinMaxGroup minmax = setupAssignments.getMinMaxGroups().get(0);
    minmax.getMinBoundedValue().setCurrentValue(min);
    minmax.getMaxBoundedValue().setCurrentValue(max);
  }
  protected void generateHistogramData(DataContainer<T> container) {
    double ch1BinWidth = getXBinWidth(container);
    double ch2BinWidth = getYBinWidth(container);

    // get the 2 images for the calculation of Pearson's
    final RandomAccessibleInterval<T> img1 = getImageCh1(container);
    final RandomAccessibleInterval<T> img2 = getImageCh2(container);
    final RandomAccessibleInterval<BitType> mask = container.getMask();

    // get the cursors for iterating through pixels in images
    TwinCursor<T> cursor =
        new TwinCursor<T>(
            img1.randomAccess(), img2.randomAccess(), Views.iterable(mask).localizingCursor());

    // create new image to put the scatter-plot in
    final ImgFactory<LongType> scatterFactory = new ArrayImgFactory<LongType>();
    plotImage = scatterFactory.create(new int[] {xBins, yBins}, new LongType());

    // create access cursors
    final RandomAccess<LongType> histogram2DCursor = plotImage.randomAccess();

    // iterate over images
    long[] pos = new long[plotImage.numDimensions()];
    while (cursor.hasNext()) {
      cursor.fwd();
      double ch1 = cursor.getFirst().getRealDouble();
      double ch2 = cursor.getSecond().getRealDouble();
      /* Scale values for both channels to fit in the range.
       * Moreover mirror the y value on the x axis.
       */
      pos[0] = getXValue(ch1, ch1BinWidth, ch2, ch2BinWidth);
      pos[1] = getYValue(ch1, ch1BinWidth, ch2, ch2BinWidth);
      // set position of input/output cursor
      histogram2DCursor.setPosition(pos);
      // get current value at position and increment it
      long count = histogram2DCursor.get().getIntegerLong();
      count++;

      histogram2DCursor.get().set(count);
    }

    xBinWidth = ch1BinWidth;
    yBinWidth = ch2BinWidth;
    xLabel = getLabelCh1();
    yLabel = getLabelCh2();
    xMin = getXMin(container);
    xMax = getXMax(container);
    yMin = getYMin(container);
    yMax = getYMax(container);
  }
  public static <T extends Type<T> & Comparable<T>> int findLocalMaximaNeighborhood2(
      final RandomAccessibleInterval<T> img) {
    // final ArrayList< Point > maxima = new ArrayList< Point >();
    int nMaxima = 0;

    final Cursor<T> center =
        Views.iterable(Views.interval(img, Intervals.expand(img, -1))).localizingCursor();
    final LocalNeighborhood2<T> neighborhood = new LocalNeighborhood2<T>(img, center);
    final LocalNeighborhoodCursor2<T> nc = neighborhood.cursor();
    A:
    while (center.hasNext()) {
      final T t = center.next();
      neighborhood.updateCenter(center);
      nc.reset();
      while (nc.hasNext()) {
        final T n = nc.next();
        if (n.compareTo(t) > 0) continue A;
      }
      // maxima.add( new Point( center ) );
      ++nMaxima;
    }
    return nMaxima;
  }
Beispiel #24
0
  /**
   * Computes a Gaussian convolution in-place (temporary imgs are necessary) with float precision on
   * an entire {@link Img}
   *
   * @param sigma - the sigma for the convolution
   * @param img - the img {@link Img} that will be convolved in place
   */
  public static <T extends RealType<T>> void inFloatInPlace(
      final double[] sigma,
      final Img<T> img,
      final OutOfBoundsFactory<FloatType, RandomAccessibleInterval<FloatType>> outofbounds) {
    GaussFloat gauss = null;
    try {
      if (FloatType.class.isInstance(img.firstElement())) {
        @SuppressWarnings({"rawtypes", "unchecked"})
        final Img<FloatType> img2 = (Img) img;
        gauss =
            new GaussFloat(
                sigma,
                Views.extend(img2, outofbounds),
                img2,
                img2,
                new Point(sigma.length),
                img2.factory().imgFactory(new FloatType()));
      } else {
        final RandomAccessibleInterval<FloatType> rIn =
            new WriteConvertedIterableRandomAccessibleInterval<T, FloatType, Img<T>>(
                img, new RealFloatSamplerConverter<T>());
        gauss =
            new GaussFloat(
                sigma,
                Views.extend(rIn, outofbounds),
                img,
                rIn,
                new Point(sigma.length),
                img.factory().imgFactory(new FloatType()));
      }
    } catch (final IncompatibleTypeException e) {
      System.out.println(e);
      return;
    }

    gauss.call();
  }
Beispiel #25
0
  private static final <R extends RealType<R>> Img<R> processReal(
      final Img<R> img, final float[] m, final Mode mode, final OutOfBoundsFactory<R, Img<R>> oobf)
      throws Exception {
    final InterpolatorFactory<R, RandomAccessible<R>> inter;
    switch (mode) {
      case LINEAR:
        inter = new NLinearInterpolatorFactory<R>();
        break;
      case NEAREST_NEIGHBOR:
        inter = new NearestNeighborInterpolatorFactory<R>();
        break;
      default:
        throw new IllegalArgumentException("Scale: don't know how to scale with mode " + mode);
    }

    final ImageTransform<R> transform;
    final ExtendedRandomAccessibleInterval<R, Img<R>> imgExt = Views.extend(img, oobf);

    if (2 == img.numDimensions()) {
      // Transform the single-plane image in 2D
      AffineModel2D aff = new AffineModel2D();
      aff.set(m[0], m[4], m[1], m[5], m[3], m[7]);
      transform = new ImageTransform<R>(imgExt, aff, (InterpolatorFactory) inter);
    } else if (3 == img.numDimensions()) {
      // Transform the image in 3D, or each plane in 2D
      if (m.length < 12) {
        throw new IllegalArgumentException(
            "Affine transform in 3D requires a matrix array of 12 elements.");
      }
      AffineModel3D aff = new AffineModel3D();
      aff.set(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11]);
      transform = new ImageTransform<R>(imgExt, aff, (InterpolatorFactory) inter);
      // Ensure Z dimension is not altered if scaleZ is 1:
      if (Math.abs(m[10] - 1.0f) < 0.000001 && 0 == m[8] && 0 == m[9]) {
        long[] d = transform.getNewImageSize();
        d[2] = img.dimension(2); // 0-based: '2' is the third dimension
        transform.setNewImageSize(d);
      }
    } else {
      throw new Exception("Affine transform: only 2D and 3D images are supported.");
    }

    if (!transform.checkInput() || !transform.process()) {
      throw new Exception("Could not affine transform the image: " + transform.getErrorMessage());
    }

    return transform.getResult();
  }
Beispiel #26
0
 public static final <T extends RealType<T>> void addGaussianSpotToImage(
     RandomAccessibleInterval<T> img, double[] params) {
   IterableInterval<T> iterImg = Views.iterable(img);
   Cursor<T> lc = iterImg.localizingCursor();
   int nDims = img.numDimensions();
   double[] position = new double[nDims];
   double val;
   T var = iterImg.firstElement().createVariable();
   while (lc.hasNext()) {
     lc.fwd();
     lc.localize(position);
     val = gaussian.val(position, params);
     var.setReal(val);
     lc.get().add(var);
   }
 }
Beispiel #27
0
  private void computeDataMinMax(final RandomAccessibleInterval<? extends RealType<?>> img) {
    // FIXME: Reconcile this with DefaultDatasetView.autoscale(int). There is
    // no reason to hardcode the usage of ComputeMinMax twice. Rather, there
    // should be a single entry point for obtain the channel min/maxes from
    // the metadata, and if they aren't there, then compute them. Probably
    // Dataset (not DatasetView) is a good place for it, because it is metadata
    // independent of the visualization settings.

    DataRange range = autoscaleService.getDefaultRandomAccessRange(img);
    dataMin = range.getMin();
    dataMax = range.getMax();
    // System.out.println("IN HERE!!!!!!");
    // System.out.println(" dataMin = " + dataMin);
    // System.out.println(" dataMax = " + dataMax);
    @SuppressWarnings({"unchecked", "rawtypes"})
    Iterable<T> iterable =
        Views.iterable((RandomAccessibleInterval<T>) (RandomAccessibleInterval) img);
    BinMapper1d<T> mapper = new Real1dBinMapper<T>(dataMin, dataMax, 256, false);
    Histogram1d<T> histogram = new Histogram1d<T>(iterable, mapper);
    if (bundle == null) {
      bundle = new HistogramBundle(histogram);
    } else {
      bundle.setHistogram(histogram);
    }
    bundle.setDataMinMax(dataMin, dataMax);
    // bundle.setLineSlopeIntercept(1, 0);
    log.debug("computeDataMinMax: dataMin=" + dataMin + ", dataMax=" + dataMax);
    // force a widget refresh to see new Hist (and also fill min and max fields)
    // NOPE. HistBundle is unchanged. Only internals are. So no
    // refresh called. Note that I changed InteractiveCommand::update() to
    // always setValue() and still this did not work. !!!! Huh?
    // update(getInfo().getMutableInput("bundle", HistogramBundle.class),
    // bundle);
    // NOPE
    // getInfo().getInput("bundle", HistogramBundle.class).setValue(this,
    // bundle);
    // NOPE
    // getInfo().setVisible(false);
    // getInfo().setVisible(true);
    // NOPE
    // getInfo().getMutableInput("bundle",HistogramBundle.class).initialize(this);
    // NOPE
    // getInfo().getMutableInput("bundle",HistogramBundle.class).callback(this);
  }
Beispiel #28
0
  private boolean processSlice(
      final RandomAccessibleInterval<FloatType> src,
      final RandomAccessibleInterval<FloatType> dx,
      final RandomAccessibleInterval<FloatType> dy) {
    // Gaussian filter.
    final ExtendedRandomAccessibleInterval<FloatType, RandomAccessibleInterval<FloatType>>
        extended = Views.extendMirrorSingle(src);
    try {
      Gauss3.gauss(new double[] {sigma, sigma}, extended, src, numThreads);
    } catch (final IncompatibleTypeException e) {
      errorMessage = BASE_ERROR_MSG + "Incompatible types: " + e.getMessage();
      e.printStackTrace();
      return false;
    }

    // Derivatives
    PartialDerivative.gradientCentralDifference(extended, dx, 0);
    PartialDerivative.gradientCentralDifference(extended, dy, 1);

    return true;
  }
  private static void adjustForOSEM(
      final HashMap<ViewId, RandomAccessibleInterval<FloatType>> weights,
      final WeightType weightType,
      final double osemspeedup) {
    if (osemspeedup == 1.0) return;

    if (weightType == WeightType.PRECOMPUTED_WEIGHTS
        || weightType == WeightType.WEIGHTS_ONLY
        || weightType == WeightType.LOAD_WEIGHTS) {
      for (final RandomAccessibleInterval<FloatType> w : weights.values()) {
        for (final FloatType f : Views.iterable(w))
          f.set(
              Math.min(
                  1, f.get() * (float) osemspeedup)); // individual contribution never higher than 1
      }
    } else if (weightType == WeightType.NO_WEIGHTS) {
      for (final RandomAccessibleInterval<FloatType> w : weights.values()) {
        final RandomAccess<FloatType> r = w.randomAccess();
        final long[] min = new long[w.numDimensions()];
        w.min(min);
        r.setPosition(min);
        r.get()
            .set(
                Math.min(
                    1,
                    r.get().get()
                        * (float) osemspeedup)); // individual contribution never higher than 1
      }
    } else if (weightType == WeightType.VIRTUAL_WEIGHTS) {
      for (final RandomAccessibleInterval<FloatType> w : weights.values())
        ((NormalizingRandomAccessibleInterval<FloatType>) w).setOSEMspeedup(osemspeedup);
    } else {
      throw new RuntimeException(
          "Weight Type: "
              + weightType.name()
              + " not supported in ProcessForDeconvolution.adjustForOSEM()");
    }
  }
  public Align(final RandomAccessibleInterval<T> template, final ImgFactory<T> factory) {
    this.template = template;
    final T type = Util.getTypeFromInterval(template);

    n = template.numDimensions();
    warpFunction = new AffineWarp(n);
    numParameters = warpFunction.numParameters();
    currentTransform = new AffineTransform(n);

    final long[] dim = new long[n + 1];
    for (int d = 0; d < n; ++d) dim[d] = template.dimension(d);
    dim[n] = n;
    final Img<T> gradients = factory.create(dim, type);
    gradients(Views.extendBorder(template), gradients);

    dim[n] = numParameters;
    descent = factory.create(dim, type);
    computeSteepestDescents(gradients, warpFunction, descent);

    Hinv = computeInverseHessian(descent);

    error = factory.create(template, type);
  }