net.imglib2.view.Views Java Examples

The following examples show how to use net.imglib2.view.Views. 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: CommitCanvasN5.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
private static <I extends IntegerType<I> & NativeType<I>> void writeBlocksLabelIntegerType(
		final RandomAccessibleInterval<UnsignedLongType> canvas,
		final long[] blocks,
		final DatasetSpec datasetSpec,
		final BlockSpec blockSpec,
		final TLongObjectHashMap<BlockDiff> blockDiff) throws IOException {
	final RandomAccessibleInterval<I> highestResolutionData = N5Utils.open(datasetSpec.container, datasetSpec.dataset);
	final I i = Util.getTypeFromInterval(highestResolutionData).createVariable();
	for (final long blockId : blocks) {
		blockSpec.fromLinearIndex(blockId);
		final RandomAccessibleInterval<Pair<I, UnsignedLongType>> backgroundWithCanvas = Views.interval(Views.pair(highestResolutionData, canvas), blockSpec.asInterval());
		final RandomAccessibleInterval<I> mergedData = Converters.convert(backgroundWithCanvas, (s, t) -> pickFirstIfSecondIsInvalid(s.getA(), s.getB(), t), i.createVariable());
		N5Utils.saveBlock(mergedData, datasetSpec.container, datasetSpec.dataset, datasetSpec.attributes, blockSpec.pos);
		blockDiff.put(blockId, createBlockDiffFromCanvasIntegerType(Views.iterable(backgroundWithCanvas)));
	}
}
 
Example #2
Source File: DoGTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void dogRAITest() {

	final double[] sigmas1 = new double[] { 1, 1 };
	final double[] sigmas2 = new double[] { 2, 2 };
	final long[] dims = new long[] { 10, 10 };

	final Img<ByteType> in = generateByteArrayTestImg(true, dims);
	final Img<ByteType> out1 = generateByteArrayTestImg(false, dims);
	final Img<ByteType> out2 = generateByteArrayTestImg(false, dims);

	ops.run(DoGVaryingSigmas.class, out1, in, sigmas1, sigmas2);

	// test against native imglib2 implementation
	DifferenceOfGaussian.DoG(sigmas1, sigmas2, Views.extendMirrorSingle(in),
		out2, Executors.newFixedThreadPool(10));

	final Cursor<ByteType> out1Cursor = out1.cursor();
	final Cursor<ByteType> out2Cursor = out2.cursor();

	while (out1Cursor.hasNext()) {
		org.junit.Assert.assertEquals(out1Cursor.next().getRealDouble(),
			out2Cursor.next().getRealDouble(), 0);
	}
}
 
Example #3
Source File: MVDeconFFTThreads.java    From SPIM_Registration with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
final protected static void convolve1BlockCUDA(
		final Block blockStruct, final int deviceId, final Img< FloatType > image,
		final Img< FloatType > result, final Img< FloatType > block, final Img< FloatType > kernel1, final int i )
{
	long time = System.currentTimeMillis();
	blockStruct.copyBlock( Views.extendMirrorSingle( image ), block );
	System.out.println( " block " + i + "(CPU  " + deviceId + "): copy " + (System.currentTimeMillis() - time) );

	// convolve block with kernel1 using CUDA
	time = System.currentTimeMillis();
	final float[] blockF = ((FloatArray)((ArrayImg< net.imglib2.type.numeric.real.FloatType, ? > )block).update( null ) ).getCurrentStorageArray();
	final float[] kernel1F = ((FloatArray)((ArrayImg< net.imglib2.type.numeric.real.FloatType, ? > )kernel1).update( null ) ).getCurrentStorageArray();
	
	MVDeconFFT.cuda.convolution3DfftCUDAInPlace(
			blockF, getCUDACoordinates( CUDAOutput.getImgSizeInt( block ) ),
			kernel1F, getCUDACoordinates( CUDAOutput.getImgSizeInt( kernel1 ) ),
			deviceId );
	System.out.println( " block " + i + "(CUDA " + deviceId + "): compute " + (System.currentTimeMillis() - time) );

	time = System.currentTimeMillis();
	blockStruct.pasteBlock( result, block );
	System.out.println( " block " + i + "(CPU  " + deviceId + "): paste " + (System.currentTimeMillis() - time) );
}
 
Example #4
Source File: IdSelector.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
private void selectAllLabelMultisetType(final TLongSet allIds)
{
	@SuppressWarnings("unchecked")
	final RandomAccessibleInterval<LabelMultisetType> data = (RandomAccessibleInterval<LabelMultisetType>)
			source.getDataSource(0, source.getNumMipmapLevels() - 1);

	final Cursor<LabelMultisetType> cursor = Views.iterable(data).cursor();
	while (cursor.hasNext())
	{
		final LabelMultisetType lmt = cursor.next();
		for (final Entry<Label> entry : lmt.entrySet())
		{
			final long id = entry.getElement().id();
			if (foregroundCheck.test(id))
				allIds.add(id);
		}
	}
}
 
Example #5
Source File: Align.java    From BigStitcher with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Compute the partial derivative of source in a particular dimension.
 *
 * @param source
 *            source image, has to provide valid data in the interval of the
 *            gradient image plus a one pixel border in dimension.
 * @param target
 *            output image, the partial derivative of source in the
 *            specified dimension.
 * @param dimension
 *            along which dimension the partial derivatives are computed
 * @param <T> pixel type source
 * @param <S> pixel type target
 */
public static < T extends RealType< T >, S extends RealType< S > > void gradient(
		final RandomAccessible< T > source,
		final RandomAccessibleInterval< S > target,
		final int dimension )
{
	final Cursor< T > front = Views.flatIterable(
			Views.interval( source,
					Intervals.translate( target, 1, dimension ) ) ).cursor();
	final Cursor< T > back = Views.flatIterable(
			Views.interval( source,
					Intervals.translate( target, -1, dimension ) ) ).cursor();
	for( final S t : Views.flatIterable( target ) )
	{
		t.setReal( front.next().getRealDouble() - back.next().getRealDouble());
		t.mul( 0.5 );
	}
}
 
Example #6
Source File: ShearViewTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Tests {@link DefaultShearView}. */
@Test
public void defaultShearTest() {
	Img<DoubleType> img = new ArrayImgFactory<DoubleType>().create(new int[] { 2, 2 }, new DoubleType());
	Cursor<DoubleType> imgC = img.cursor();
	while (imgC.hasNext()) {
		imgC.next().set(1);
	}

	TransformView<DoubleType> il2 = Views.shear(Views.extendZero(img), 0, 1);
	TransformView<DoubleType> opr = ops.transform().shearView(Views.extendZero(img), 0, 1);
	Cursor<DoubleType> il2C = Views.interval(il2, new FinalInterval(new long[] { 0, 0 }, new long[] { 3, 3 }))
			.cursor();
	RandomAccess<DoubleType> oprRA = Views
			.interval(opr, new FinalInterval(new long[] { 0, 0 }, new long[] { 3, 3 })).randomAccess();

	while (il2C.hasNext()) {
		il2C.next();
		oprRA.setPosition(il2C);
		assertEquals(il2C.get().get(), oprRA.get().get(), 1e-10);
	}
}
 
Example #7
Source File: OutlineTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Test the op with a 3x3 square with a hole in the middle. The square is in
 * the middle of a 5x5 img
 */
@Test
public void testOutlineSquare() {
	// SETUP
	final Img<BitType> img = ArrayImgs.bits(5, 5);
	final IntervalView<BitType> square = Views.offsetInterval(img, new long[] {
		1, 1 }, new long[] { 3, 3 });
	square.cursor().forEachRemaining(BitType::setOne);
	final RandomAccess<BitType> access = square.randomAccess();
	access.setPosition(new long[] { 1, 1 });
	access.get().setZero();

	// EXECUTION
	final Img<BitType> result = (Img<BitType>) ops.morphology().outline(img,
		Boolean.TRUE);

	// VERIFY
	assertEquals("Wrong number of foreground elements in interval", 8,
		countForeground(result));
	final IntervalView<BitType> resultSquare = Views.offsetInterval(result,
		new long[] { 1, 1 }, new long[] { 3, 3 });
	assertEquals("Wrong number of foreground elements in object", 8,
		countForeground(resultSquare));
	assertPositionBackground(result, new long[] { 2, 2 });
}
 
Example #8
Source File: DefaultDoG.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void compute(final RandomAccessibleInterval<T> input,
	final RandomAccessibleInterval<T> output)
{
	// input may potentially be translated
	final long[] translation = new long[input.numDimensions()];
	input.min(translation);

	final IntervalView<T> tmpInterval = Views.interval(Views.translate(
		(RandomAccessible<T>) tmpCreator.calculate(input), translation), output);

	gauss1.compute(input, tmpInterval);
	gauss2.compute(input, output);

	// TODO: Match the Subtract Op in initialize() once we have BinaryOp
	ops().run(Ops.Math.Subtract.class, output, output, tmpInterval);
}
 
Example #9
Source File: LocalThresholdIntegral.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Add 0s before axis minimum.
 * 
 * @param input Input RAI
 * @return An extended and cropped version of input
 */
private <T extends RealType<T>> RandomAccessibleInterval<T> addLeadingZeros(
	RandomAccessibleInterval<T> input)
{
	final long[] min = Intervals.minAsLongArray(input);
	final long[] max = Intervals.maxAsLongArray(input);

	for (int i = 0; i < max.length; i++) {
		min[i]--;
	}

	final T realZero = Util.getTypeFromInterval(input).copy();
	realZero.setZero();

	final ExtendedRandomAccessibleInterval<T, RandomAccessibleInterval<T>> extendedImg = Views.extendValue(input,
		realZero);
	final IntervalView<T> offsetInterval = Views.interval(extendedImg,
		min, max);
	
	return Views.zeroMin(offsetInterval);
}
 
Example #10
Source File: DefaultDilate.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void compute(final RandomAccessibleInterval<T> in1, final Shape in2,
	final IterableInterval<T> output)
{
	final RandomAccessibleInterval<T> shifted;
	if (isFull) {
		final long[] offset = MorphologyUtils
			.computeTargetImageDimensionsAndOffset(in1, in2)[1];
		shifted = Views.translate(in1, offset);
	}
	else {
		shifted = in1;
	}
	final ExtendedRandomAccessibleInterval<T, RandomAccessibleInterval<T>> extended =
		Views.extend(shifted, f);
	Dilation.dilate(extended, output, in2, minVal, Runtime.getRuntime()
		.availableProcessors());
}
 
Example #11
Source File: TranslateViewTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testIntervalTranslate() {
	Img<DoubleType> img = ArrayImgs.doubles(10,10);

	IntervalView<DoubleType> expected = Views.translate(img, 2, 5);
	IntervalView<DoubleType> actual = ops.transform().translateView(img, 2, 5);

	for (int i = 0; i < ((MixedTransformView<DoubleType>) expected.getSource()).getTransformToSource().getMatrix().length; i++) {
		for (int j = 0; j < ((MixedTransformView<DoubleType>) expected.getSource()).getTransformToSource().getMatrix()[i].length; j++) {
			assertEquals(((MixedTransformView<DoubleType>) expected.getSource()).getTransformToSource().getMatrix()[i][j], ((MixedTransformView<DoubleType>) actual.getSource()).getTransformToSource().getMatrix()[i][j],
					1e-10);
		}
	}
	
	assertTrue(Intervals.equals(expected, actual));
}
 
Example #12
Source File: ShearViewTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Tests {@link ShearViewInterval}. */
@Test
public void ShearIntervalTest() {
	Img<DoubleType> img = new ArrayImgFactory<DoubleType>().create(new int[] { 2, 2 }, new DoubleType());
	Cursor<DoubleType> imgC = img.cursor();
	while (imgC.hasNext()) {
		imgC.next().set(1);
	}

	Cursor<DoubleType> il2 = Views
			.shear(Views.extendZero(img), new FinalInterval(new long[] { 0, 0 }, new long[] { 3, 3 }), 0, 1)
			.cursor();
	RandomAccess<DoubleType> opr = ops.transform()
			.shearView(Views.extendZero(img), new FinalInterval(new long[] { 0, 0 }, new long[] { 3, 3 }), 0, 1)
			.randomAccess();

	while (il2.hasNext()) {
		il2.next();
		opr.setPosition(il2);
		assertEquals(il2.get().get(), opr.get().get(), 1e-10);
	}
}
 
Example #13
Source File: SliceTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testNonZeroMinimumInterval() {

	Img<ByteType> img3D = ArrayImgs.bytes(50, 50, 3);
	IntervalView<ByteType> interval2D = Views.interval(img3D,
			new FinalInterval(new long[] { 25, 25, 2 }, new long[] { 35, 35, 2 }));
	final int[] xyAxis = new int[] { 0, 1 };

	// iterate through every slice, should return a single
	// RandomAccessibleInterval<?> from 25, 25, 2 to 35, 35, 2

	final SlicesII<ByteType> hyperSlices = new SlicesII<>(interval2D, xyAxis, true);
	final Cursor<RandomAccessibleInterval<ByteType>> c = hyperSlices.cursor();
	int i = 0;
	while (c.hasNext()) {
		c.next();
		i++;
	}

	assertEquals(1, i);
}
 
Example #14
Source File: BoxCountTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testHyperCube() {
	// SETUP
	final double[] expectedSizes = DoubleStream.of(4, 2, 1).map(i -> -Math.log(
		i)).toArray();
	final double[] expectedCounts = DoubleStream.of(1, 16, 16).map(Math::log)
		.toArray();
	final Img<BitType> img = ArrayImgs.bits(4, 4, 4, 4);
	final IntervalView<BitType> hyperView = Views.offsetInterval(img,
		new long[] { 1, 1, 1, 1 }, new long[] { 2, 2, 2, 2 });
	hyperView.forEach(BitType::setOne);

	// EXECUTE
	final List<ValuePair<DoubleType, DoubleType>> points = ops.topology()
		.boxCount(img, 4L, 1L, 2.0);

	// VERIFY
	for (int i = 0; i < expectedSizes.length; i++) {
		assertEquals(expectedSizes[i], points.get(i).a.get(), 1e-12);
		assertEquals(expectedCounts[i], points.get(i).b.get(), 1e-12);
	}
}
 
Example #15
Source File: RasterViewTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void defaultRasterTest() {
	Img<DoubleType> img = new ArrayImgFactory<DoubleType>().create(new int[]{10,  10}, new DoubleType());
	MersenneTwisterFast r = new MersenneTwisterFast(SEED);
	for (DoubleType d : img) {
		d.set(r.nextDouble());
	}
	RealRandomAccessible<DoubleType> realImg = Views.interpolate(img, new FloorInterpolatorFactory<DoubleType>());
	
	RandomAccessibleOnRealRandomAccessible<DoubleType> il2 = Views.raster(realImg);
	RandomAccessibleOnRealRandomAccessible<DoubleType> opr = ops.transform().rasterView(realImg);
	
	Cursor<DoubleType> il2C = Views.interval(il2, img).localizingCursor();
	RandomAccess<DoubleType> oprRA = Views.interval(opr, img).randomAccess();
	
	while (il2C.hasNext()) {
		il2C.next();
		oprRA.setPosition(il2C);
		assertEquals(il2C.get().get(), oprRA.get().get(), 1e-10);
	}
}
 
Example #16
Source File: ColocalisationTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Gaussian Smooth of the input image using intermediate float format.
 * 
 * @param <T>
 * @param img
 * @param sigma
 * @return
 */
public static <T extends RealType<T> & NativeType<T>>
	Img<T> gaussianSmooth(RandomAccessibleInterval<T> img,
		double[] sigma)
{
	Interval interval = Views.iterable(img);

	ImgFactory<T> outputFactory = new ArrayImgFactory<>(Util.getTypeFromInterval(img));
	final long[] dim = new long[img.numDimensions()];
	img.dimensions(dim);
	Img<T> output = outputFactory.create(dim);

	final long[] pos = new long[img.numDimensions()];
	Arrays.fill(pos, 0);
	Localizable origin = new Point(pos);

	ImgFactory<FloatType> tempFactory = new ArrayImgFactory<>(new FloatType());
	RandomAccessible<T> input = Views.extendMirrorSingle(img);
	Gauss.inFloat(sigma, input, interval, output, origin, tempFactory);

	return output;
}
 
Example #17
Source File: InvertAxisViewTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void intervalInvertAxisTest() {

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

	final IntervalView<DoubleType> il2 = Views.invertAxis(img, 1);
	final IntervalView<DoubleType> opr = ops.transform().invertAxisView(img, 1);

	for (int i = 0; i < ((MixedTransformView<DoubleType>) il2.getSource()).getTransformToSource()
			.getMatrix().length; i++) {
		for (int j = 0; j < ((MixedTransformView<DoubleType>) il2.getSource()).getTransformToSource()
				.getMatrix()[i].length; j++) {
			assertEquals(
					((MixedTransformView<DoubleType>) il2.getSource()).getTransformToSource().getMatrix()[i][j],
					((MixedTransformView<DoubleType>) opr.getSource()).getTransformToSource().getMatrix()[i][j],
					1e-10);
		}
	}
}
 
Example #18
Source File: PhaseCorrelation2.java    From BigStitcher with GNU General Public License v2.0 6 votes vote down vote up
public static <T extends RealType<T>, S extends RealType<S>, R extends RealType<R>, C extends ComplexType<C>> RandomAccessibleInterval<R> calculatePCM(
		RandomAccessibleInterval<T> img1, RandomAccessibleInterval<S> img2, int[] extension,
		ImgFactory<R> factory, R type, ImgFactory<C> fftFactory, C fftType, ExecutorService service){

	
	// TODO: Extension absolute per dimension in pixels, i.e. int[] extension
	// TODO: not bigger than the image dimension because the second mirroring is identical to the image
	
	Dimensions extSize = PhaseCorrelation2Util.getExtendedSize(img1, img2, extension);
	long[] paddedDimensions = new long[extSize.numDimensions()];
	long[] fftSize = new long[extSize.numDimensions()];
	FFTMethods.dimensionsRealToComplexFast(extSize, paddedDimensions, fftSize);
	
	RandomAccessibleInterval<C> fft1 = fftFactory.create(fftSize, fftType);
	RandomAccessibleInterval<C> fft2 = fftFactory.create(fftSize, fftType);
	
	FFT.realToComplex(Views.interval(PhaseCorrelation2Util.extendImageByFactor(img1, extension), 
			FFTMethods.paddingIntervalCentered(img1, new FinalInterval(paddedDimensions))), fft1, service);
	FFT.realToComplex(Views.interval(PhaseCorrelation2Util.extendImageByFactor(img2, extension), 
			FFTMethods.paddingIntervalCentered(img2, new FinalInterval(paddedDimensions))), fft2, service);
	
	RandomAccessibleInterval<R> pcm = calculatePCMInPlace(fft1, fft2, factory, type, service);
	return pcm;
	
}
 
Example #19
Source File: MVDeconFFTThreads.java    From SPIM_Registration with GNU General Public License v2.0 6 votes vote down vote up
final protected static void convolve1BlockCPU(
		final Block blockStruct, final Img< FloatType > image, final Img< FloatType > result,
		final Img< FloatType > block, final FFTConvolution< FloatType > fftConvolution1, final int i )
{
	long time = System.currentTimeMillis();
	blockStruct.copyBlock( Views.extendMirrorSingle( image ), block );
	System.out.println( " block " + i + "(CPU): copy " + (System.currentTimeMillis() - time) );

	time = System.currentTimeMillis();
	fftConvolution1.setImg( block );
	fftConvolution1.setOutput( block );
	fftConvolution1.convolve();
	System.out.println( " block " + i + "(CPU): compute " + (System.currentTimeMillis() - time) );

	time = System.currentTimeMillis();
	blockStruct.pasteBlock( result, block );
	System.out.println( " block " + i + "(CPU): paste " + (System.currentTimeMillis() - time) );
}
 
Example #20
Source File: LiICQ.java    From Colocalisation_Analysis with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void execute(DataContainer<T> container)
		throws MissingPreconditionException {
	double mean1 = container.getMeanCh1();
	double mean2 = container.getMeanCh2();

	// get the 2 images for the calculation of Li's ICQ
	RandomAccessible<T> img1 = container.getSourceImage1();
	RandomAccessible<T> img2 = container.getSourceImage2();
	RandomAccessibleInterval<BitType> mask = container.getMask();

	TwinCursor<T> cursor = new TwinCursor<T>(img1.randomAccess(),
			img2.randomAccess(), Views.iterable(mask).localizingCursor());
	// calculate ICQ value
	icqValue = calculateLisICQ(cursor, mean1, mean2);
}
 
Example #21
Source File: ImageStatistics.java    From Colocalisation_Analysis with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Calculates the integral of the pixel values of an image.
 *
 * @param img The image to calculate the integral of
 * @return The pixel values integral of the image passed
 */
final public static <T extends RealType<T>> double getImageIntegral(
		final RandomAccessibleInterval<T> img,
		final RandomAccessibleInterval<BitType> mask )
{
	final RealSum sum = new RealSum();
	// 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).cursor());
	while (cursor.hasNext())
		sum.add( cursor.getFirst().getRealDouble() );

	return sum.getSum();
}
 
Example #22
Source File: PermuteViewTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void defaultPermuteCoordinatesInverseTest() {
	Img<DoubleType> img = new ArrayImgFactory<DoubleType>().create(new int[]{2, 2}, new DoubleType());
	Cursor<DoubleType> c = img.cursor();
	MersenneTwisterFast r = new MersenneTwisterFast(SEED);
	while (c.hasNext()) {
		c.next().set(r.nextDouble());
	}
	Cursor<DoubleType> il2 = Views.permuteCoordinatesInverse(img, new int[]{0, 1}).cursor();
	RandomAccess<DoubleType> opr = ops.transform().permuteCoordinatesInverseView(img, new int[]{0, 1}).randomAccess();
	
	while (il2.hasNext()) {
		il2.next();
		opr.setPosition(il2);
		assertEquals(il2.get().get(), opr.get().get(), 1e-10);
	}
}
 
Example #23
Source File: PermuteViewTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testIntervalPermuteDimensionCoordinates() {
	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}, 1);
	Cursor<DoubleType> e = expected.cursor();
	RandomAccessibleInterval<DoubleType> actual = ops.transform().permuteCoordinatesView(img, new int[]{0, 1}, 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 #24
Source File: WatershedTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void test() {
	// load test image
	Img<FloatType> watershedTestImg = openFloatImg(WatershedTest.class, "watershed_test_image.png");

	// threshold it
	RandomAccessibleInterval<BitType> thresholdedImg = ops.create().img(watershedTestImg, new BitType());
	ops.threshold().apply(Views.flatIterable(thresholdedImg), Views.flatIterable(watershedTestImg),
			new FloatType(1));

	// compute inverted distance transform and smooth it with gaussian
	// filtering
	final RandomAccessibleInterval<FloatType> distMap = ops.image().distancetransform(thresholdedImg);
	final RandomAccessibleInterval<FloatType> invertedDistMap = ops.create().img(distMap, new FloatType());
	ops.image().invert(Views.iterable(invertedDistMap), Views.iterable(distMap));
	final RandomAccessibleInterval<FloatType> gauss = ops.filter().gauss(invertedDistMap, 3, 3);

	testWithoutMask(gauss);

	testWithMask(gauss);
}
 
Example #25
Source File: PermuteViewTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testIntervalPermuteInverseCoordinates() {
	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.permuteCoordinatesInverse(img, new int[]{0, 1});
	Cursor<DoubleType> e = expected.cursor();
	RandomAccessibleInterval<DoubleType> actual = ops.transform().permuteCoordinatesInverseView(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 #26
Source File: MVDeconFFTThreads.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
final protected static void convolve2BlockCPU(
		final Block blockStruct, final Img< FloatType > image, final Img< FloatType > result,
		final Img< FloatType > block, final FFTConvolution< FloatType > fftConvolution2 )
{
	// ratio outside of the deconvolved space (psi) is 1
	blockStruct.copyBlock( Views.extendValue( image, new FloatType( 1.0f ) ), block );

	fftConvolution2.setImg( block );
	fftConvolution2.setOutput( block );
	fftConvolution2.convolve();
	
	blockStruct.pasteBlock( result, block );
}
 
Example #27
Source File: PainteraAlerts.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
private static long findMaxId(final RandomAccessibleInterval<? extends IntegerType<?>> rai) {
	long maxId = org.janelia.saalfeldlab.labels.Label.getINVALID();
	for (final IntegerType<?> t : Views.iterable(rai)) {
		final long id = t.getIntegerLong();
		if (id > maxId)
			maxId = id;
	}
	return maxId;
}
 
Example #28
Source File: RichardsonLucyTVUpdate.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * performs update step of the Richardson Lucy with Total Variation Algorithm
 */
@Override
public void compute(I correction, I estimate) {

	if (variation == null) {
		Type<T> type = Util.getTypeFromInterval(correction);

		variation = ops().create().img(correction, type.createVariable());
	}

	divUnitGradFastThread(estimate);

	final Cursor<T> cursorCorrection = Views.iterable(correction).cursor();

	final Cursor<T> cursorVariation = Views.iterable(variation).cursor();

	final Cursor<T> cursorEstimate = Views.iterable(estimate).cursor();

	while (cursorEstimate.hasNext()) {
		cursorCorrection.fwd();
		cursorVariation.fwd();
		cursorEstimate.fwd();

		cursorEstimate.get().mul(cursorCorrection.get());
		cursorEstimate.get().mul(1f / (1f - regularizationFactor * cursorVariation
			.get().getRealFloat()));
	}

}
 
Example #29
Source File: MandersColocalization.java    From Colocalisation_Analysis with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void execute(DataContainer<T> container)
		throws MissingPreconditionException {
	// get the two images for the calculation of Manders' split coefficients
	RandomAccessible<T> img1 = container.getSourceImage1();
	RandomAccessible<T> img2 = container.getSourceImage2();
	RandomAccessibleInterval<BitType> mask = container.getMask();

	TwinCursor<T> cursor = new TwinCursor<T>(img1.randomAccess(),
			img2.randomAccess(), Views.iterable(mask).localizingCursor());

	// calculate Manders' split coefficients without threshold, M1 and M2.
	MandersResults results = calculateMandersCorrelation(cursor,
			img1.randomAccess().get().createVariable());

	// save the results
	mandersM1 = results.m1;
	mandersM2 = results.m2;

	// calculate the thresholded Manders' split coefficients, tM1 and tM2, if possible
	AutoThresholdRegression<T> autoThreshold = container.getAutoThreshold();
	if (autoThreshold != null ) {
		// thresholded Manders' split coefficients, tM1 and tM2
		cursor.reset();
		results = calculateMandersCorrelation(cursor, autoThreshold.getCh1MaxThreshold(),
				autoThreshold.getCh2MaxThreshold(), ThresholdMode.Above);

		// save the results
		mandersThresholdedM1 = results.m1;
		mandersThresholdedM2 = results.m2;
	}
}
 
Example #30
Source File: OffsetViewTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void defaultOffsetIntervalTest() {

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

	IntervalView<DoubleType> il2 = Views.offsetInterval(img,
			new FinalInterval(new long[] { 2, 2 }, new long[] { 9, 9 }));
	IntervalView<DoubleType> opr = ops.transform().offsetView(img,
			new FinalInterval(new long[] { 2, 2 }, new long[] { 9, 9 }));

	assertEquals(il2.realMax(0), opr.realMax(0), 1e-10);
	assertEquals(il2.realMin(0), opr.realMin(0), 1e-10);
	assertEquals(il2.realMax(1), opr.realMax(1), 1e-10);
	assertEquals(il2.realMin(1), opr.realMin(1), 1e-10);
}