Java Code Examples for net.imglib2.RandomAccessibleInterval#randomAccess()

The following examples show how to use net.imglib2.RandomAccessibleInterval#randomAccess() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EulerCharacteristic26N.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void compute(RandomAccessibleInterval<B> interval, DoubleType output) {
    final RandomAccess<B> access = interval.randomAccess();
    long sumDeltaEuler = 0;

    for (long z = 0; z < interval.dimension(2) - 1; z++) {
        for (long y = 0; y < interval.dimension(1) - 1; y++) {
            for (long x = 0; x < interval.dimension(0) - 1; x++) {
                int index = neighborhoodEulerIndex(access, x, y, z);
                sumDeltaEuler += EULER_LUT[index];
            }
        }
    }

    output.set(sumDeltaEuler / 8.0);
}
 
Example 2
Source File: Maps.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static <I1, I2, O> void map(final RandomAccessibleInterval<I1> a,
	final IterableInterval<I2> b, final RandomAccessibleInterval<O> c,
	final BinaryComputerOp<I1, I2, O> op, final long startIndex,
	final long stepSize, final long numSteps)
{
	if (numSteps <= 0) return;
	final RandomAccess<I1> aAccess = a.randomAccess();
	final Cursor<I2> bCursor = b.localizingCursor();
	final RandomAccess<O> cAccess = c.randomAccess();

	for (long ctr = 0; ctr < numSteps; ctr++) {
		bCursor.jumpFwd(ctr == 0 ? startIndex + 1 : stepSize);
		aAccess.setPosition(bCursor);
		cAccess.setPosition(bCursor);
		op.compute(aAccess.get(), bCursor.get(), cAccess.get());
	}
}
 
Example 3
Source File: PermuteViewTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testIntervalPermuteCoordinates() {
	Img<DoubleType> img = ArrayImgs.doubles(2, 2);
	Cursor<DoubleType> c = img.cursor();
	MersenneTwisterFast r = new MersenneTwisterFast(SEED);
	while (c.hasNext()) {
		c.next().set(r.nextDouble());
	}
	IntervalView<DoubleType> expected = Views.permuteCoordinates(img, new int[]{0, 1});
	Cursor<DoubleType> e = expected.cursor();
	RandomAccessibleInterval<DoubleType> actual = ops.transform().permuteCoordinatesView(img, new int[]{0, 1});
	RandomAccess<DoubleType> actualRA = actual.randomAccess();
	
	while (e.hasNext()) {
		e.next();
		actualRA.setPosition(e);
		assertEquals(e.get().get(), actualRA.get().get(), 1e-10);
	}
	
	assertTrue(Intervals.equals(expected, actual));
	
}
 
Example 4
Source File: Maps.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static <I1, I2, O> void map(final RandomAccessibleInterval<I1> a,
	final RandomAccessibleInterval<I2> b, final IterableInterval<O> c,
	final BinaryComputerOp<I1, I2, O> op, final long startIndex,
	final long stepSize, final long numSteps)
{
	if (numSteps <= 0) return;
	final RandomAccess<I1> aAccess = a.randomAccess();
	final RandomAccess<I2> bAccess = b.randomAccess();
	final Cursor<O> cCursor = c.localizingCursor();

	for (long ctr = 0; ctr < numSteps; ctr++) {
		cCursor.jumpFwd(ctr == 0 ? startIndex + 1 : stepSize);
		aAccess.setPosition(cCursor);
		bAccess.setPosition(cCursor);
		op.compute(aAccess.get(), bAccess.get(), cCursor.get());
	}
}
 
Example 5
Source File: ImageStatistics.java    From Colocalisation_Analysis with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Calculates the max of an image with respect to a mask.
 *
 * @param img The image to calculate the min of
 * @param mask The mask to respect
 * @return The min of the image passed
 */
final public static <T extends Type<T> & Comparable<T>> T getImageMax(
		final RandomAccessibleInterval<T> img,
		final RandomAccessibleInterval<BitType> mask )
{
	// create cursor to walk an image with respect to a mask
	final TwinCursor<T> cursor = new TwinCursor<T>(
			img.randomAccess(),
			img.randomAccess(),
			Views.iterable(mask).localizingCursor());
	// forward one step to get the first value
	cursor.fwd();
	final T max = cursor.getFirst().copy();

	while ( cursor.hasNext() ) {
		cursor.fwd();

		final T currValue = cursor.getFirst();

		if ( currValue.compareTo( max ) > 0 )
			max.set( currValue );
	}

       return max;
 }
 
Example 6
Source File: DefaultDerivativeGauss.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Convolves the rows of the image
 *
 * @param input - The input image.
 * @param output - The output image.
 * @param mask - The mask needed for the convolution, determined beforehand.
 */
private <T extends RealType<T>> void convolve_n(
	final RandomAccessibleInterval<T> input,
	final RandomAccessibleInterval<DoubleType> output, final double[] mask,
	final int n)
{
	double sum;
	final Cursor<T> cursor = Views.iterable(input).localizingCursor();
	final OutOfBoundsMirrorFactory<T, RandomAccessibleInterval<T>> osmf =
		new OutOfBoundsMirrorFactory<>(Boundary.SINGLE);
	final RandomAccess<T> inputRA = osmf.create(input);
	final RandomAccess<DoubleType> outputRA = output.randomAccess();

	while (cursor.hasNext()) {
		cursor.fwd();
		inputRA.setPosition(cursor);
		outputRA.setPosition(cursor);
		sum = 0;
		// loop from the bottom of the image to the top
		final int halfWidth = mask.length / 2;
		for (int i = -halfWidth; i <= halfWidth; i++) {
			for (int dim = 0; dim < input.numDimensions(); dim++) {
				long position = cursor.getLongPosition(dim);
				if (dim == n) position += i;
				inputRA.setPosition(position, dim);
			}
			sum += inputRA.get().getRealDouble() * mask[i + halfWidth];
		}
		outputRA.get().setReal(sum);
	}
}
 
Example 7
Source File: DefaultFloodFill.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void compute(RandomAccessibleInterval<T> op0, Localizable loc,
	RandomAccessibleInterval<T> r)
{
	final RandomAccess<T> op0c = op0.randomAccess();
	op0c.setPosition(loc);
	final T fillValue = op0c.get().copy();
	FloodFill.fill(Views.extendValue(op0, fillValue), Views.extendValue(r, fillValue), loc, fillValue, structElement, new Filter<Pair<T,T >, Pair<T,T>>() {

		@Override
		public boolean accept(Pair<T, T> t, Pair<T, T> u) {
			return !t.getB().valueEquals(u.getB()) && t.getA().valueEquals(u.getA());
		}
	});
}
 
Example 8
Source File: BoxCount.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Creates a task for parallel calculation of foreground boxes.
 *
 * @param dimensions Size of input image in each dimension
 * @param boxSize Size of a box (n * n * ... n)
 * @param translation Starting position of the box grid
 * @param first Number of the first box for this thread
 * @param input The input interval.
 * @param boxes Number of boxes this thread counts
 * @param <B> type of the elements in the input interval
 * @return a task that counts which boxes have foreground in them.
 */
private static <B extends BooleanType<B>> Callable<Long> createCalculationTask(
		long[] dimensions, long boxSize, long[] translation, long first,
		RandomAccessibleInterval<B> input, long boxes) {
	return () -> {
		// I tried sharing a single generator between the threads,
		// but having to call next() and hasNext() in a synchronized block
		// created a bottle neck.
		final CoordinateGenerator boxer = new CoordinateGenerator(
				dimensions, boxSize, translation);
		boxer.skip(first);
		final RandomAccess<B> access = input.randomAccess();
		final long[] boxPosition = new long[access.numDimensions()];
		final long[] position = new long[access.numDimensions()];
		long foreground = 0;
		long generated = 0;
		while (generated < boxes) {
			boxer.next(boxPosition);
			final int d = access.numDimensions() - 1;
			if (hasBoxForeground(d, access, boxPosition, boxSize,
					dimensions, position)) {
				foreground++;
			}
			generated++;
		}
		return foreground;
	};
}
 
Example 9
Source File: Maps.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static <I, O> void map(final RandomAccessibleInterval<I> a,
	final IterableInterval<O> b, final UnaryComputerOp<I, O> op,
	final long startIndex, final long stepSize, final long numSteps)
{
	if (numSteps <= 0) return;
	final RandomAccess<I> aAccess = a.randomAccess();
	final Cursor<O> bCursor = b.localizingCursor();

	for (long ctr = 0; ctr < numSteps; ctr++) {
		bCursor.jumpFwd(ctr == 0 ? startIndex + 1 : stepSize);
		aAccess.setPosition(bCursor);
		op.compute(aAccess.get(), bCursor.get());
	}
}
 
Example 10
Source File: DistanceTransform2DTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void generate2DImg(final RandomAccessibleInterval<BitType> in) {
	final RandomAccess<BitType> raIn = in.randomAccess();
	final MersenneTwisterFast random = new MersenneTwisterFast(SEED);

	for (int x = 0; x < in.dimension(0); x++) {
		for (int y = 0; y < in.dimension(1); y++) {
			raIn.setPosition(new int[] { x, y });
			raIn.get().set(random.nextBoolean());
		}
	}
}
 
Example 11
Source File: DefaultDistanceTransformCalibration.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public InitPhaseCal(final double[] actualValues, final RandomAccessibleInterval<B> raIn, final int[] dimensSizes,
		final int[] positions, final double[] calibration) {
	this.actualValues = actualValues;
	this.raIn = raIn.randomAccess();
	int inf = 0;
	for (int i = 0; i < dimensSizes.length; i++)
		inf += calibration[i] * calibration[i] * dimensSizes[i] * dimensSizes[i];
	this.infinite = inf;
	this.dimensSizes = dimensSizes;
	this.positions = positions;
	this.calibration = calibration;
}
 
Example 12
Source File: MaskAndRoiTest.java    From Colocalisation_Analysis with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void regularRoiPixelCountTest() {
	// load a 3D test image
	RandomAccessibleInterval<UnsignedByteType> img = positiveCorrelationImageCh1;
	final long[] roiOffset = createRoiOffset(img);
	final long[] roiSize = createRoiSize(img);
	final long width = img.dimension(0);
	final long height = img.dimension(1);

	RandomAccessibleInterval<UnsignedByteType> maskImg
		= TestImageAccessor.createRectengularMaskImage(width, height, roiOffset, roiSize);
	final long[] dim = new long[ img.numDimensions() ];
	img.dimensions(dim);
	RandomAccessibleInterval<BitType> mask =
			MaskFactory.createMask(dim, maskImg);

	TwinCursor<UnsignedByteType> cursor = new TwinCursor<UnsignedByteType>(
			img.randomAccess(),
			img.randomAccess(),
			Views.iterable(mask).localizingCursor());
	// calculate volume of mask bounding box
	long roiVolume = roiSize[0] * roiSize[1] * img.dimension(2);
	long count = 0;
	while (cursor.hasNext()) {
		cursor.fwd();
		count++;
	}

	assertEquals(roiVolume, count);
}
 
Example 13
Source File: Maps.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static <I, O> void map(final RandomAccessibleInterval<I> a,
	final IterableInterval<O> b, final UnaryComputerOp<I, O> op)
{
	final RandomAccess<I> aAccess = a.randomAccess();
	final Cursor<O> bCursor = b.localizingCursor();
	while (bCursor.hasNext()) {
		bCursor.fwd();
		aAccess.setPosition(bCursor);
		op.compute(aAccess.get(), bCursor.get());
	}
}
 
Example 14
Source File: DistanceTransform3DTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void compareResults(final RandomAccessibleInterval<FloatType> out,
		final RandomAccessibleInterval<BitType> in, final double[] calibration) {
	final RandomAccess<FloatType> raOut = out.randomAccess();
	final RandomAccess<BitType> raIn = in.randomAccess();
	for (int x0 = 0; x0 < in.dimension(0); x0++) {
		for (int y0 = 0; y0 < in.dimension(1); y0++) {
			for (int z0 = 0; z0 < in.dimension(2); z0++) {
				raIn.setPosition(new int[] { x0, y0, z0 });
				raOut.setPosition(new int[] { x0, y0, z0 });
				if (!raIn.get().get()) {
					assertEquals(0, raOut.get().get(), EPSILON);
				} else {
					double actualValue = in.dimension(0) * in.dimension(0) + in.dimension(1) * in.dimension(1)
							+ in.dimension(2) * in.dimension(2);
					for (int x = 0; x < in.dimension(0); x++) {
						for (int y = 0; y < in.dimension(1); y++) {
							for (int z = 0; z < in.dimension(2); z++) {
								raIn.setPosition(new int[] { x, y, z });
								final double dist = calibration[0] * calibration[0] * (x0 - x) * (x0 - x)
										+ calibration[1] * calibration[1] * (y0 - y) * (y0 - y)
										+ calibration[2] * calibration[2] * (z0 - z) * (z0 - z);
								if ((!raIn.get().get()) && (dist < actualValue))
									actualValue = dist;
							}
						}
					}
					assertEquals(Math.sqrt(actualValue), raOut.get().get(), EPSILON);
				}
			}
		}
	}
}
 
Example 15
Source File: Maps.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static <I1, I2, O extends I1> void inplace(
	final IterableInterval<O> arg, final RandomAccessibleInterval<I2> in,
	final BinaryInplace1Op<I1, I2, O> op)
{
	final Cursor<O> argCursor = arg.localizingCursor();
	final RandomAccess<I2> inAccess = in.randomAccess();
	while (argCursor.hasNext()) {
		argCursor.fwd();
		inAccess.setPosition(argCursor);
		op.mutate1(argCursor.get(), inAccess.get());
	}
}
 
Example 16
Source File: ContentBased.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
protected Img< FloatType > approximateEntropy(
		final RandomAccessibleInterval< FloatType > input,
		final ImgFactory< ComplexFloatType > imgFactory,
		final double[] sigma1,
		final double[] sigma2 )

{
	// the result
	ImgFactory<FloatType> f;
	try { f = imgFactory.imgFactory( new FloatType() ); } catch (IncompatibleTypeException e) { f = new ArrayImgFactory< FloatType >(); }
	
	final Img< FloatType > conv = f.create( input, new FloatType() );
	
	// compute I*sigma1
	FFTConvolution< FloatType > fftConv = new FFTConvolution<FloatType>( input, createGaussianKernel( sigma1 ), conv, imgFactory );
	fftConv.convolve();
	
	// compute ( I - I*sigma1 )^2
	final Cursor< FloatType > c = conv.cursor();
	final RandomAccess< FloatType > r = input.randomAccess();
	
	while ( c.hasNext() )
	{
		c.fwd();
		r.setPosition( c );
		
		final float diff = c.get().get() - r.get().get();
		c.get().set( diff * diff );
	}
	
	// compute ( ( I - I*sigma1 )^2 ) * sigma2
	fftConv = new FFTConvolution<FloatType>( conv, createGaussianKernel( sigma2 ), imgFactory );
	fftConv.convolve();

	// normalize to [0...1]
	FusionHelper.normalizeImage( conv );

	return conv;
}
 
Example 17
Source File: Coloc_2.java    From Colocalisation_Analysis with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This method duplicates the given images, but respects ROIs if present.
 * Meaning, a sub-picture will be created when source images are
 * ROI/MaskImages.
 * 
 * @throws MissingPreconditionException
 */
protected RandomAccessibleInterval<T> createMaskImage(
	final RandomAccessibleInterval<T> image,
	final RandomAccessibleInterval<BitType> mask, final long[] offset,
	final long[] size) throws MissingPreconditionException
{
	final long[] pos = new long[image.numDimensions()];
	// sanity check
	if (pos.length != offset.length || pos.length != size.length) {
		throw new MissingPreconditionException(
			"Mask offset and size must be of same dimensionality like image.");
	}
	// use twin cursor for only one image
	final TwinCursor<T> cursor = new TwinCursor<>(image.randomAccess(), //
		image.randomAccess(), Views.iterable(mask).localizingCursor());
	// prepare output image
	final ImgFactory<T> maskFactory = new ArrayImgFactory<>();
	// Img<T> maskImage = maskFactory.create( size, name );
	final RandomAccessibleInterval<T> maskImage = maskFactory.create(size, //
		image.randomAccess().get().createVariable());
	final RandomAccess<T> maskCursor = maskImage.randomAccess();
	// go through the visible data and copy it to the output
	while (cursor.hasNext()) {
		cursor.fwd();
		cursor.localize(pos);
		// shift coordinates by offset
		for (int i = 0; i < pos.length; ++i) {
			pos[i] = pos[i] - offset[i];
		}
		// write out to correct position
		maskCursor.setPosition(pos);
		maskCursor.get().set(cursor.getFirst());
	}

	return maskImage;
}
 
Example 18
Source File: MorphologyOpsTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testFillHoles2() {
	RandomAccessibleInterval<BitType> result = ops.morphology().fillHoles(imgWithoutHoles);
	Cursor<BitType> groundTruthC = imgWithoutHoles.localizingCursor();
	RandomAccess<BitType> resultRA = result.randomAccess();

	while (groundTruthC.hasNext()) {
		boolean r = groundTruthC.next().get();
		resultRA.setPosition(groundTruthC);
		assertEquals(r, resultRA.get().get());
	}
}
 
Example 19
Source File: DefaultDistanceTransformTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void compareResults(final RandomAccessibleInterval<FloatType> out,
		final RandomAccessibleInterval<BitType> in, final double[] calibration) {
	final RandomAccess<FloatType> raOut = out.randomAccess();
	final RandomAccess<BitType> raIn = in.randomAccess();
	for (int x0 = 0; x0 < in.dimension(0); x0++) {
		for (int y0 = 0; y0 < in.dimension(1); y0++) {
			for (int z0 = 0; z0 < in.dimension(2); z0++) {
				for (int w0 = 0; w0 < in.dimension(3); w0++) {
					raIn.setPosition(new int[] { x0, y0, z0, w0 });
					raOut.setPosition(new int[] { x0, y0, z0, w0 });
					if (!raIn.get().get()) {
						assertEquals(0, raOut.get().get(), EPSILON);
					} else {
						double actualValue = in.dimension(0) * in.dimension(0) + in.dimension(1) * in.dimension(1)
								+ in.dimension(2) * in.dimension(2) + in.dimension(3) * in.dimension(3);
						for (int x = 0; x < in.dimension(0); x++) {
							for (int y = 0; y < in.dimension(1); y++) {
								for (int z = 0; z < in.dimension(2); z++) {
									for (int w = 0; w < in.dimension(3); w++) {
										raIn.setPosition(new int[] { x, y, z, w });
										final double dist = calibration[0] * calibration[0] * (x0 - x) * (x0 - x)
												+ calibration[1] * calibration[1] * (y0 - y) * (y0 - y)
												+ calibration[2] * calibration[2] * (z0 - z) * (z0 - z)
												+ calibration[3] * calibration[3] * (w0 - w) * (w0 - w);

										if ((!raIn.get().get()) && (dist < actualValue))
											actualValue = dist;
									}
								}
							}
						}
						assertEquals(Math.sqrt(actualValue), raOut.get().get(), EPSILON);
					}
				}
			}
		}
	}
}
 
Example 20
Source File: RestrictPainting.java    From paintera with GNU General Public License v2.0 4 votes vote down vote up
private static void restrictToLabelMultisetType(
		final MaskedSource<LabelMultisetType, ?> source,
		final int time,
		final int level,
		final Localizable seed,
		final Runnable requestRepaint) throws MaskInUse
{
	final RandomAccessibleInterval<UnsignedLongType>  canvas        = source.getReadOnlyDataCanvas(time, level);
	final RandomAccessibleInterval<LabelMultisetType> background    = source.getReadOnlyDataBackground(time,
			level);
	final MaskInfo<UnsignedLongType>                  maskInfo      = new MaskInfo<>(
			time,
			level,
			new UnsignedLongType(Label.TRANSPARENT)
	);
	final Mask<UnsignedLongType> mask = source.generateMask(maskInfo, FOREGROUND_CHECK);
	final AccessBoxRandomAccessible<UnsignedLongType> accessTracker = new AccessBoxRandomAccessible<>(Views
			.extendValue(mask.mask, new UnsignedLongType(1)));

	final RandomAccess<UnsignedLongType> canvasAccess = canvas.randomAccess();
	canvasAccess.setPosition(seed);
	final UnsignedLongType                paintedLabel     = canvasAccess.get();
	final RandomAccess<LabelMultisetType> backgroundAccess = background.randomAccess();
	backgroundAccess.setPosition(seed);
	final LabelMultisetType backgroundSeed      = backgroundAccess.get();
	final long              backgroundSeedLabel = backgroundSeed.entrySet().stream().max((e1, e2) -> Long.compare(
			e1.getCount(),
			e2.getCount()
	                                                                                                             )
	                                                                                    ).map(
			e -> e.getElement().id()).orElse(Label.INVALID);

	final RandomAccessible<Pair<LabelMultisetType, UnsignedLongType>> paired = Views.pair(
			Views.extendValue(
					background,
					new LabelMultisetType()
			                 ),
			Views.extendValue(canvas, new UnsignedLongType(Label.INVALID))
	                                                                                     );

	restrictTo(
			paired,
			accessTracker,
			seed,
			new DiamondShape(1),
			bg -> bg.contains(backgroundSeedLabel),
			cv -> cv.valueEquals(paintedLabel)
	          );

	requestRepaint.run();

	source.applyMask(mask, accessTracker.createAccessInterval(), FOREGROUND_CHECK);

}