net.imglib2.util.Intervals Java Examples

The following examples show how to use net.imglib2.util.Intervals. 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: 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 #2
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 #3
Source File: FitToInterval.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onChanged(final Change<? extends Source<?>> change)
{
	while (change.next())
		if (change.wasAdded() && change.getList().size() == 1)
		{
			final Source<?>         addedSource = change.getAddedSubList().get(0);
			final double[]          min         = Arrays.stream(Intervals.minAsLongArray(addedSource.getSource(
					0,
					0
			                                                                                                  ))).asDoubleStream().toArray();
			final double[]          max         = Arrays.stream(Intervals.maxAsLongArray(addedSource.getSource(
					0,
					0
			                                                                                                  ))).asDoubleStream().toArray();
			final AffineTransform3D tf          = new AffineTransform3D();
			addedSource.getSourceTransform(0, 0, tf);
			tf.apply(min, min);
			tf.apply(max, max);
			fitToInterval.fit(Intervals.smallestContainingInterval(new FinalRealInterval(min, max)));
		}

}
 
Example #4
Source File: AbstractOpTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public ListImg<UnboundedIntegerType> generateUnboundedIntegerTypeListTestImg(
	final boolean fill, final long... dims)
{

	final ListImg<UnboundedIntegerType> l =
		new ListImgFactory<UnboundedIntegerType>().create(dims,
			new UnboundedIntegerType());

	final BigInteger[] array = new BigInteger[(int) Intervals.numElements(
		dims)];

	RandomAccess<UnboundedIntegerType> ra = l.randomAccess();

	if (fill) {
		MersenneTwisterFast betterRNG = new MersenneTwisterFast(0xf1eece);
		for (int i = 0; i < Intervals.numElements(dims); i++) {
			BigInteger val = BigInteger.valueOf(betterRNG.nextLong());
			ra.get().set(val);
			ra.fwd(0);
		}
	}

	return l;
}
 
Example #5
Source File: MultiResolutionRendererGeneric.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Request a repaint of the given display interval from the painter thread. The painter thread will trigger a {@link #paint} as
 * soon as possible (that is, immediately or after the currently running {@link #paint} has completed).
 */
public synchronized void requestRepaint(final Interval interval, final int screenScaleIndex)
{
	if (Intervals.isEmpty(interval))
		return;

	if (renderingMayBeCancelled && projector != null)
		projector.cancel();

	if (screenScaleIndex > requestedScreenScaleIndex)
		requestedScreenScaleIndex = screenScaleIndex;

	// FIXME: there is a race condition that sometimes may cause an ArrayIndexOutOfBounds exception:
	// Screen scales are first initialized with the default setting (see RenderUnit),
	// then the project metadata is loaded, and the screen scales are changed to the saved configuration.
	// If the project screen scales are [1.0], sometimes the renderer receives a request to re-render the screen at screen scale 1, which results in the exception.
	if (requestedScreenScaleIndex >= pendingRepaintRequests.length)
		return;

	if (pendingRepaintRequests[requestedScreenScaleIndex] == null)
		pendingRepaintRequests[requestedScreenScaleIndex] = interval;
	else
		pendingRepaintRequests[requestedScreenScaleIndex] = Intervals.union(pendingRepaintRequests[requestedScreenScaleIndex], interval);

	painterThread.requestRepaint();
}
 
Example #6
Source File: DefaultJsonServiceTest.java    From imagej-server with Apache License 2.0 6 votes vote down vote up
@Test
public void deserializeSpecialTypes() throws Exception {
	final LinkedHashMap<String, Object> inputs = new LinkedHashMap<>();
	final ByteType type = new ByteType();
	final Img<ByteType> img0 = Imgs.create(new ArrayImgFactory<>(type),
		Intervals.createMinMax(0, 10, 0, 10), type);
	final Img<ByteType> img1 = Imgs.create(new PlanarImgFactory<>(type),
		Intervals.createMinMax(0, 10, 0, 10), type);
	final Foo foo = new Foo("test string");
	inputs.put("img0", img0);
	inputs.put("img1", img1);
	inputs.put("foo", foo);

	objectService.register(img0, "");
	objectService.register(img1, "");
	objectService.register(foo, "");

	@SuppressWarnings("unchecked")
	final Map<String, Object> deserialized = modifiedMapper.readValue(fixture(
		"fixtures/inputs/specialTypes.json"), Map.class);

	assertEquals(deserialized, inputs);
}
 
Example #7
Source File: Fusion.java    From SPIM_Registration with GNU General Public License v2.0 6 votes vote down vote up
protected long computeAvgImageSize()
{
	long avgSize = 0;
	int countImgs = 0;

	for ( final ViewId viewId : viewIdsToProcess  )
	{
		final ViewDescription desc = spimData.getSequenceDescription().getViewDescription( viewId );

		if ( desc.isPresent() )
		{
			final ViewSetup viewSetup = desc.getViewSetup();
			final long numPixel = Intervals.numElements( ViewSetupUtils.getSizeOrLoad( viewSetup, desc.getTimePoint(), spimData.getSequenceDescription().getImgLoader() ) );

			avgSize += numPixel;
			++countImgs;
		}
	}
	
	return avgSize / countImgs;
}
 
Example #8
Source File: ShapeInterpolationMode.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
private SectionInfo createSectionInfo(final PainteraBaseView paintera)
{
	Interval selectionSourceBoundingBox = null;
	for (final TLongObjectIterator<SelectedObjectInfo> it = selectedObjects.iterator(); it.hasNext();)
	{
		it.advance();
		if (selectionSourceBoundingBox == null)
			selectionSourceBoundingBox = it.value().sourceBoundingBox;
		else
			selectionSourceBoundingBox = Intervals.union(selectionSourceBoundingBox, it.value().sourceBoundingBox);
	}

	final AffineTransform3D globalTransform = new AffineTransform3D();
	paintera.manager().getTransform(globalTransform);

	return new SectionInfo(
			mask,
			globalTransform,
			getMaskDisplayTransformIgnoreScaling(SHAPE_INTERPOLATION_SCALE_LEVEL),
			selectionSourceBoundingBox,
			new TLongObjectHashMap<>(selectedObjects)
		);
}
 
Example #9
Source File: MeshGeneratorJobManager.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
private ShapeKey<T> createShapeKey(
		final CellGrid grid,
		final long index,
		final int scaleLevel,
		final SceneUpdateParameters sceneUpdateParameters)
{
	final Interval blockInterval = Grids.getCellInterval(grid, index);
	return new ShapeKey<>(
			identifier,
			scaleLevel,
			sceneUpdateParameters.simplificationIterations,
			sceneUpdateParameters.smoothingLambda,
			sceneUpdateParameters.smoothingIterations,
			sceneUpdateParameters.minLabelRatio,
			Intervals.minAsLongArray(blockInterval),
			Intervals.maxAsLongArray(blockInterval)
		);
}
 
Example #10
Source File: MTKT.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public Double calculate(final RandomAccessibleInterval<T> image1, final RandomAccessibleInterval<U> image2) {
	// check image sizes
	// TODO: Add these checks to conforms().
	if (!(Intervals.equalDimensions(image1, image2))) {
		throw new IllegalArgumentException("Image dimensions do not match");
	}
	final long n1 = Intervals.numElements(image1);
	if (n1 > Integer.MAX_VALUE) {
		throw new IllegalArgumentException("Image dimensions too large: " + n1);
	}
	final int n = (int) n1;

	// compute thresholds
	final double thresh1 = threshold(image1);
	final double thresh2 = threshold(image2);

	double[][] rank = rankTransformation(image1, image2, thresh1, thresh2, n, seed);

	double maxtau = calculateMaxKendallTau(rank, thresh1, thresh2, n);
	return maxtau;
}
 
Example #11
Source File: AbstractOpTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public ArrayImg<UnsignedVariableBitLengthType, LongArray>
	generateUnsignedVariableBitLengthTypeArrayTestImg(final boolean fill,
		final int nbits, final long... dims)
{
	final long[] array = new long[(int) Intervals.numElements(new FinalInterval(
		dims))];

	if (fill) {
		seed = 17;
		for (int i = 0; i < array.length; i++) {
			array[i] = (long) (((pseudoRandom() / Integer.MAX_VALUE)) % (Math.pow(2, nbits))) ;
		}
	}

	final LongArray l = new LongArray(array);

	return ArrayImgs.unsignedVariableBitLengths(l, nbits, dims);
}
 
Example #12
Source File: DefaultCoarsenessFeature.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Apply mean filter with given size of reactangle shape
 * 
 * @param input
 *            Input image
 * @param i
 *            Size of rectangle shape
 * @return Filered mean image
 */
@SuppressWarnings("unchecked")
private Img<I> mean(final RandomAccessibleInterval<I> input, final int i) {

	long[] dims = new long[input.numDimensions()];
	input.dimensions(dims);

	final byte[] array = new byte[(int) Intervals.numElements(new FinalInterval(dims))];
	Img<I> meanImg = (Img<I>) ArrayImgs.unsignedBytes(array, dims);

	OutOfBoundsMirrorFactory<ByteType, Img<ByteType>> oobFactory = new OutOfBoundsMirrorFactory<>(
			Boundary.SINGLE);

	ops().run(MeanFilterOp.class, meanImg, input, new RectangleShape(i, true), oobFactory);

	return meanImg;
}
 
Example #13
Source File: SubsampleViewTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testIntervalSubsampleSteps() {
	Img<DoubleType> img = ArrayImgs.doubles(10,10);
	MersenneTwisterFast r = new MersenneTwisterFast(SEED);
	for (DoubleType d : img) {
		d.set(r.nextDouble());
	}

	SubsampleIntervalView<DoubleType> expected = Views.subsample((RandomAccessibleInterval<DoubleType>) img, 2, 1);
	SubsampleIntervalView<DoubleType> actual = (SubsampleIntervalView<DoubleType>) ops.transform().subsampleView((RandomAccessibleInterval<DoubleType>)img, 2, 1);

	Cursor<DoubleType> il2C = Views.interval(expected, new long[] { 0, 0 }, new long[] { 4, 9 }).localizingCursor();
	RandomAccess<DoubleType> oprRA = actual.randomAccess();

	while (il2C.hasNext()) {
		il2C.next();
		oprRA.setPosition(il2C);
		assertEquals(il2C.get().get(), oprRA.get().get(), 1e-10);
	}
	
	assertTrue(Intervals.equals(expected, actual));
}
 
Example #14
Source File: VolatileHierarchyProjectorPreMultiply.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
public VolatileHierarchyProjectorPreMultiply(
		final List<? extends RandomAccessible<A>> sources,
		final Converter<? super A, ARGBType> converter,
		final RandomAccessibleInterval<ARGBType> target,
		final int numThreads,
		final ExecutorService executorService)
{
	this(
			sources,
			converter,
			target,
			ArrayImgs.bytes(Intervals.dimensionsAsLongArray(target)),
			numThreads,
			executorService
	    );
}
 
Example #15
Source File: BlendedExtendedMirroredRandomAccesible2.java    From BigStitcher with GNU General Public License v2.0 6 votes vote down vote up
public BlendedExtendedMirroredRandomAccesible2(RandomAccessibleInterval<T> img, int[] border) {
	this.img = img;
	this.numDimensions = img.numDimensions();
	
	float[] blendingBorder = new float[numDimensions];
	float[] border2 = new float[numDimensions];
	
	this.extDims = new FinalInterval(img);		
	for (int i = 0; i < numDimensions; i++)
	{
		extDims = Intervals.expand(extDims, border[i], i);
		blendingBorder[i] = border[i];
		border2[i] = 0.0f;
	}
	
	this.blending = new BlendingRealRandomAccessible(extDims, border2, blendingBorder);
}
 
Example #16
Source File: CreateImgTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testImageMinimum() {

	final MersenneTwisterFast randomGenerator = new MersenneTwisterFast(SEED);

	for (int i = 0; i < TEST_SIZE; i++) {

		// between 2 and 5 dimensions
		final long[] max = new long[randomGenerator.nextInt(4) + 2];
		final long[] min = new long[max.length];

		// between 2 and 10 pixels per dimensions
		for (int j = 0; j < max.length; j++) {
			max[j] = randomGenerator.nextInt(9) + 2;
			min[j] = Math.max(0, max[j] - randomGenerator.nextInt(4));
		}

		// create img
		final Img<?> img = (Img<?>) ops.run(CreateImgFromInterval.class,
			new FinalInterval(min, max));

		assertArrayEquals("Image Minimum:", min, Intervals.minAsLongArray(img));
		assertArrayEquals("Image Maximum:", max, Intervals.maxAsLongArray(img));
	}
}
 
Example #17
Source File: CommitCanvasN5Test.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
private static <T> void testCanvasPersistance(
		final N5Writer container,
		final String group,
		final String labelsDataset,
		final CachedCellImg<UnsignedLongType, ?> canvas,
		final BiFunction<N5Reader, String, RandomAccessibleInterval<T>> openLabels,
		final BiConsumer<UnsignedLongType, T> asserts) throws IOException, UnableToPersistCanvas, UnableToUpdateLabelBlockLookup {

	writeAll(container, group, canvas);

	final RandomAccessibleInterval<T> labels = openLabels.apply(container, labelsDataset);
	Assert.assertArrayEquals(Intervals.dimensionsAsLongArray(canvas), Intervals.dimensionsAsLongArray(labels));

	for (final Pair<UnsignedLongType, T> pair : Views.interval(Views.pair(canvas, labels), labels)) {
		LOG.trace("Comparing canvas {} and background {}", pair.getA(), pair.getB());
		asserts.accept(pair.getA(), pair.getB());
	}
}
 
Example #18
Source File: CreateLabelingTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testImageDimensions() {

	final MersenneTwisterFast randomGenerator = new MersenneTwisterFast(SEED);

	for (int i = 0; i < TEST_SIZE; i++) {

		// between 2 and 5 dimensions
		final long[] dim = new long[randomGenerator.nextInt(4) + 2];

		// between 2 and 10 pixels per dimensions
		for (int j = 0; j < dim.length; j++) {
			dim[j] = randomGenerator.nextInt(9) + 2;
		}

		// create imglabeling
		@SuppressWarnings("unchecked")
		final ImgLabeling<String, ?> img = (ImgLabeling<String, ?>) ops.run(
			DefaultCreateImgLabeling.class, dim);

		assertArrayEquals("Labeling Dimensions:", dim, Intervals
			.dimensionsAsLongArray(img));
	}
}
 
Example #19
Source File: Grids.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get all blocks/cells of a {@link CellGrid} that the real interval defined by {@code min} and {@code max}
 * intersects with, represented as linear indices.
 * @param min top-left corner of interval
 * @param max bottom-right corner of interval
 * @param cellGrid defines grid (block size/cell size)
 * @return linear indices of all cells/blocks that intersect with interval defined by {@code min}, {@code max}.
 */
public static long[] getIntersectingBlocks(
		final long[] min,
		final long[] max,
		final CellGrid cellGrid)
{
	final Interval relevantInterval = snapToGrid(min, max, cellGrid);
	final int[] blockSize = new int[cellGrid.numDimensions()];
	cellGrid.cellDimensions(blockSize);
	final TLongArrayList blockIndices = new TLongArrayList();
	net.imglib2.algorithm.util.Grids.forEachOffset(
			Intervals.minAsLongArray(relevantInterval),
			Intervals.maxAsLongArray(relevantInterval),
			blockSize,
			blockOffset -> blockIndices.add(posToIndex(cellGrid, blockOffset)));
	return blockIndices.toArray();
}
 
Example #20
Source File: Grids.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get all blocks/cells of a {@link CellGrid} that the real interval defined by {@code min} and {@code max}
 * intersects with, represented as linear indices.
 * @param min top-left corner of interval
 * @param max bottom-right corner of interval
 * @param cellGrid defines grid (block size/cell size)
 * @return linear indices of all cells/blocks that intersect with interval defined by {@code min}, {@code max}.
 */
public static long[] getIntersectingBlocks(
		final double[] min,
		final double[] max,
		final CellGrid cellGrid)
{
	final Interval relevantInterval = snapToGrid(min, max, cellGrid);
	final int[] blockSize = new int[cellGrid.numDimensions()];
	cellGrid.cellDimensions(blockSize);
	final TLongArrayList blockIndices = new TLongArrayList();
	net.imglib2.algorithm.util.Grids.forEachOffset(
			Intervals.minAsLongArray(relevantInterval),
			Intervals.maxAsLongArray(relevantInterval),
			blockSize,
			blockOffset -> blockIndices.add(posToIndex(cellGrid, blockOffset)));
	return blockIndices.toArray();
}
 
Example #21
Source File: PainteraCommandLineArgs.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
private static long findMaxId(final DataSource<? extends IntegerType<?>, ?> source) {
	final RandomAccessibleInterval<? extends IntegerType<?>> rai = source.getDataSource(0, 0);

	final int[] blockSize = blockSizeFromRai(rai);
	final List<Interval> intervals = Grids.collectAllContainedIntervals(Intervals.minAsLongArray(rai), Intervals.maxAsLongArray(rai), blockSize);

	final ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
	final List<Future<Long>> futures = new ArrayList<>();
	for (final Interval interval : intervals)
		futures.add(es.submit(() -> findMaxId(Views.interval(rai, interval))));
	es.shutdown();
	final long maxId = futures
			.stream()
			.map(ThrowingFunction.unchecked(Future::get))
			.mapToLong(Long::longValue)
			.max()
			.orElse(Label.getINVALID());
	LOG.debug("Found max id {}", maxId);
	return maxId;
}
 
Example #22
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 #23
Source File: SubsampleViewTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testIntervalSubsample() {
	Img<DoubleType> img = ArrayImgs.doubles(10, 10);
	MersenneTwisterFast r = new MersenneTwisterFast(SEED);
	for (DoubleType d : img) {
		d.set(r.nextDouble());
	}

	SubsampleIntervalView<DoubleType> expected = Views.subsample((RandomAccessibleInterval<DoubleType>) img, 2);
	SubsampleIntervalView<DoubleType> actual = (SubsampleIntervalView<DoubleType>) ops.transform().subsampleView((RandomAccessibleInterval<DoubleType>)img, 2);

	Cursor<DoubleType> il2C = Views.interval(expected, new long[] { 0, 0 }, new long[] { 4, 4 }).localizingCursor();
	RandomAccess<DoubleType> oprRA = actual.randomAccess();

	while (il2C.hasNext()) {
		il2C.next();
		oprRA.setPosition(il2C);
		assertEquals(il2C.get().get(), oprRA.get().get(), 1e-10);
	}
	
	assertTrue(Intervals.equals(expected, actual));
}
 
Example #24
Source File: HistogramOfOrientedGradients2D.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public Void call() throws Exception {

	final FinalInterval interval = new FinalInterval(in.dimension(0), in.dimension(1));
	for (int j = 0; j < in.dimension(1); j++) {
		// sum up the magnitudes of all bins in a neighborhood
		raNeighbor.setPosition(new long[] { i, j });
		final Cursor<FloatType> cursorNeighborHood = raNeighbor.get().cursor();
		while (cursorNeighborHood.hasNext()) {
			cursorNeighborHood.next();
			if (Intervals.contains(interval, cursorNeighborHood)) {
				raAngles.setPosition(cursorNeighborHood);
				raMagnitudes.setPosition(cursorNeighborHood);
				raOut.setPosition(new long[] { i, j,
						(int) (raAngles.get().getRealFloat() / (360 / numOrientations) - 0.5) });
				raOut.get().add(raMagnitudes.get());
			}
		}
	}
	return null;
}
 
Example #25
Source File: Maps.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static <I1, I2, O> boolean compatible(
	final RandomAccessibleInterval<I1> a, final IterableInterval<I2> b,
	final IterableInterval<O> c)
{
	return b.iterationOrder().equals(c.iterationOrder()) && Intervals.contains(
		a, b);
}
 
Example #26
Source File: DefaultScaleView.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public RandomAccessibleInterval<T> calculate(RandomAccessibleInterval<T> input) {
	final long[] newDims = Intervals.dimensionsAsLongArray(in());
	for (int i = 0; i < Math.min(scaleFactors.length, in().numDimensions()); i++) {
		newDims[i] = Math.round(in().dimension(i) * scaleFactors[i]);
	}

	IntervalView<T> interval = Views.interval(Views.raster(RealViews.affineReal(
		Views.interpolate(Views.extendMirrorSingle(input), interpolator),
		new Scale(scaleFactors))), new FinalInterval(newDims));

	return interval;
}
 
Example #27
Source File: AbstractOpTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ArrayImg<IntType, IntArray> generateIntArrayTestImg(final boolean fill,
	final long... dims)
{
	final int[] array = new int[(int) Intervals.numElements(new FinalInterval(
		dims))];

	if (fill) {
		seed = 17;
		for (int i = 0; i < array.length; i++) {
			array[i] = (int) pseudoRandom() / (int) Integer.MAX_VALUE;
		}
	}

	return ArrayImgs.ints(array, dims);
}
 
Example #28
Source File: CreateImgTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testCreateFromImgDifferentType() {
	final Img<ByteType> input = PlanarImgs.bytes(10, 10, 10);
	final Img<?> res = (Img<?>) ops.run(CreateImgFromDimsAndType.class, input,
		new ShortType());

	assertEquals("Image Type: ", ShortType.class, res.firstElement().getClass());
	assertArrayEquals("Image Dimensions: ", Intervals
		.dimensionsAsLongArray(input), Intervals.dimensionsAsLongArray(res));
	assertEquals("Image Factory: ", input.factory().getClass(), res.factory()
		.getClass());
}
 
Example #29
Source File: WatershedBinarySingleSigma.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public boolean conforms() {
	boolean conformed = sigma >= 0;
	if (mask != null) {
		conformed &= Intervals.equalDimensions(mask, in());
	}
	return conformed;
}
 
Example #30
Source File: WatershedSeeded.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public boolean conforms() {
	boolean conformed = true;
	if (mask != null) {
		conformed = Intervals.equalDimensions(mask, in());
	}
	conformed &= Intervals.equalDimensions(seeds, in());
	return conformed;
}