Java Code Examples for net.imglib2.util.Util#getTypeFromInterval()

The following examples show how to use net.imglib2.util.Util#getTypeFromInterval() . 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: 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 2
Source File: TestImageAccessor.java    From Colocalisation_Analysis with GNU General Public License v3.0 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>> RandomAccessibleInterval<T> gaussianSmooth(
		RandomAccessibleInterval<T> img, double[] sigma) {
	Interval interval = Views.iterable(img);

	ImgFactory<T> outputFactory = new ArrayImgFactory<T>(Util.getTypeFromInterval(img));
	final long[] dim = new long[ img.numDimensions() ];
	img.dimensions(dim);
	RandomAccessibleInterval<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<FloatType>(new FloatType());
	RandomAccessible<T> input = Views.extendMirrorSingle(img);
	Gauss.inFloat(sigma, input, interval, output, origin, tempFactory);

	return output;
}
 
Example 3
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 4
Source File: ListTopHat.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void initialize() {
	openComputer = Hybrids.binaryCF(ops(), Ops.Morphology.Open.class, out(),
		in1(), in2());

	if (out() == null) setOutput(createOutput());

	final T type = Util.getTypeFromInterval(in1());
	subtractor = Inplaces.binary(ops(), Ops.Map.class, out(), Views.iterable(
		in()), Inplaces.binary(ops(), Ops.Math.Subtract.class, type, type));
}
 
Example 5
Source File: ListBlackTopHat.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void initialize() {
	closeComputer = Hybrids.binaryCF(ops(), Ops.Morphology.Close.class, out(),
		in1(), in2());

	if (out() == null) setOutput(createOutput());

	final T type = Util.getTypeFromInterval(in1());
	subtractor = Inplaces.binary1(ops(), Ops.Map.class, out(), in(), Inplaces
		.binary1(ops(), Ops.Math.Subtract.class, type, type));
}
 
Example 6
Source File: CopyRAI.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void initialize() {
	final Object outType = out() == null ? Type.class : Util
		.getTypeFromInterval(out());

	final Object inType = in() == null ? NativeType.class : Util
		.getTypeFromInterval(in());

	final UnaryComputerOp<?, ?> typeComputer = Computers.unary(ops(),
		Ops.Copy.Type.class, outType, inType);
	mapComputer = RAIs.computer(ops(), Ops.Map.class, in(), typeComputer);
	createFunc = RAIs.function(ops(), Ops.Create.Img.class, in(), inType);

}
 
Example 7
Source File: AbstractIntegralImg.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public RandomAccessibleInterval<RealType<?>> createOutput(
	final RandomAccessibleInterval<I> input)
{
	// Create integral image
	if (Util.getTypeFromInterval(input) instanceof IntegerType) {
		return createLongRAI.calculate(input);
	}

	return createDoubleRAI.calculate(input);
}
 
Example 8
Source File: DoGVaryingSigmas.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public UnaryHybridCF<RandomAccessibleInterval<T>, RandomAccessibleInterval<T>>
	createWorker(final RandomAccessibleInterval<T> t)
{
	final T type = Util.getTypeFromInterval(t);
	return RAIs.hybrid(ops(), Ops.Filter.DoG.class, t, //
		RAIs.computer(ops(), Ops.Filter.Gauss.class, t, sigmas1, fac), //
		RAIs.computer(ops(), Ops.Filter.Gauss.class, t, sigmas2, fac), //
		RAIs.function(ops(), Ops.Create.Img.class, t), //
		RAIs.function(ops(), Ops.Create.Img.class, t, type));
}
 
Example 9
Source File: N5ChannelDataSource.java    From paintera with GNU General Public License v2.0 4 votes vote down vote up
@Override
public RealComposite<D> getDataType() {
	return Util.getTypeFromInterval(getDataSource(0, 0));
}
 
Example 10
Source File: IntersectingSourceState.java    From paintera with GNU General Public License v2.0 4 votes vote down vote up
private static <D extends IntegerType<D>, T extends Type<T>, B extends BooleanType<B>>
DataSource<UnsignedByteType, VolatileUnsignedByteType> makeIntersect(
		final SourceState<B, Volatile<B>> thresholded,
		final ConnectomicsLabelState<D, T> labels,
		final SharedQueue queue,
		final int priority,
		final String name) {
	LOG.debug(
			"Number of mipmap labels: thresholded={} labels={}",
			thresholded.getDataSource().getNumMipmapLevels(),
			labels.getDataSource().getNumMipmapLevels()
	);
	if (thresholded.getDataSource().getNumMipmapLevels() != labels.getDataSource().getNumMipmapLevels()) {
		throw new RuntimeException("Incompatible sources (num mip map levels )");
	}

	final AffineTransform3D[] transforms = new AffineTransform3D[thresholded.getDataSource().getNumMipmapLevels()];
	final RandomAccessibleInterval<UnsignedByteType>[] data = new RandomAccessibleInterval[transforms.length];
	final RandomAccessibleInterval<VolatileUnsignedByteType>[] vdata = new RandomAccessibleInterval[transforms.length];
	final Invalidate<Long>[] invalidate = new Invalidate[transforms.length];
	final Invalidate<Long>[] vinvalidate = new Invalidate[transforms.length];

	final FragmentsInSelectedSegments fragmentsInSelectedSegments = new FragmentsInSelectedSegments(labels.getSelectedSegments());

	for (int level = 0; level < thresholded.getDataSource().getNumMipmapLevels(); ++level) {
		final DataSource<D, T> labelsSource = labels.getDataSource() instanceof MaskedSource<?, ?>
				? ((MaskedSource<D, T>) labels.getDataSource()).underlyingSource()
				: labels.getDataSource();
		final AffineTransform3D tf1 = new AffineTransform3D();
		final AffineTransform3D tf2 = new AffineTransform3D();
		thresholded.getDataSource().getSourceTransform(0, level, tf1);
		labelsSource.getSourceTransform(0, level, tf2);
		if (!Arrays.equals(tf1.getRowPackedCopy(), tf2.getRowPackedCopy()))
			throw new RuntimeException("Incompatible sources ( transforms )");

		final RandomAccessibleInterval<B> thresh = thresholded.getDataSource().getDataSource(0, level);
		final RandomAccessibleInterval<D> label = labelsSource.getDataSource(0, level);

		final CellGrid grid = label instanceof AbstractCellImg<?, ?, ?, ?>
				? ((AbstractCellImg<?, ?, ?, ?>) label).getCellGrid()
				: new CellGrid(
				Intervals.dimensionsAsLongArray(label),
				Arrays.stream(Intervals.dimensionsAsLongArray(label)).mapToInt(l -> (int) l)
						.toArray());

		final B extension = Util.getTypeFromInterval(thresh);
		extension.set(false);
		final LabelIntersectionCellLoader<D, B> loader = new LabelIntersectionCellLoader<>(
				label,
				Views.extendValue(thresh, extension),
				checkForType(labelsSource.getDataType(), fragmentsInSelectedSegments),
				BooleanType::get,
				extension::copy);

		LOG.debug("Making intersect for level={} with grid={}", level, grid);


		final LoadedCellCacheLoader<UnsignedByteType, VolatileByteArray> cacheLoader = LoadedCellCacheLoader.get(grid, loader, new UnsignedByteType(), AccessFlags.setOf(AccessFlags.VOLATILE));
		final Cache<Long, Cell<VolatileByteArray>> cache = new SoftRefLoaderCache<Long, Cell<VolatileByteArray>>().withLoader(cacheLoader);
		final CachedCellImg<UnsignedByteType, VolatileByteArray> img = new CachedCellImg<>(grid, new UnsignedByteType(), cache, new VolatileByteArray(1, true));
		// TODO cannot use VolatileViews because we need access to cache
		final TmpVolatileHelpers.RaiWithInvalidate<VolatileUnsignedByteType> vimg = TmpVolatileHelpers.createVolatileCachedCellImgWithInvalidate(
				img,
				queue,
				new CacheHints(LoadingStrategy.VOLATILE, priority, true));
		data[level] = img;
		vdata[level] = vimg.getRai();
		invalidate[level] = img.getCache();
		vinvalidate[level] = vimg.getInvalidate();
		transforms[level] = tf1;
	}

	return new RandomAccessibleIntervalDataSource<>(
			new ValueTriple<>(data, vdata, transforms),
			new InvalidateDelegates<>(Arrays.asList(new InvalidateDelegates<>(invalidate), new InvalidateDelegates<>(vinvalidate))),
			Interpolations.nearestNeighbor(),
			Interpolations.nearestNeighbor(),
			name);
}
 
Example 11
Source File: IntersectingSourceState.java    From paintera with GNU General Public License v2.0 4 votes vote down vote up
@Deprecated
private static <D extends IntegerType<D>, T extends Type<T>, B extends BooleanType<B>>
DataSource<UnsignedByteType, VolatileUnsignedByteType> makeIntersect(
		final SourceState<B, Volatile<B>> thresholded,
		final LabelSourceState<D, T> labels,
		final SharedQueue queue,
		final int priority,
		final String name) {
	LOG.debug(
			"Number of mipmap labels: thresholded={} labels={}",
			thresholded.getDataSource().getNumMipmapLevels(),
			labels.getDataSource().getNumMipmapLevels()
	         );
	if (thresholded.getDataSource().getNumMipmapLevels() != labels.getDataSource().getNumMipmapLevels())
	{
		throw new RuntimeException("Incompatible sources (num mip map levels )");
	}

	final AffineTransform3D[]                                  transforms = new AffineTransform3D[thresholded.getDataSource().getNumMipmapLevels()];
	final RandomAccessibleInterval<UnsignedByteType>[]         data       = new RandomAccessibleInterval[transforms.length];
	final RandomAccessibleInterval<VolatileUnsignedByteType>[] vdata      = new RandomAccessibleInterval[transforms.length];
	final Invalidate<Long>[] invalidate                                   = new Invalidate[transforms.length];
	final Invalidate<Long>[] vinvalidate                                  = new Invalidate[transforms.length];

	final SelectedIds                    selectedIds                 = labels.selectedIds();
	final FragmentSegmentAssignmentState assignment                  = labels.assignment();
	final SelectedSegments               selectedSegments            = new SelectedSegments(
			selectedIds,
			assignment);
	final FragmentsInSelectedSegments    fragmentsInSelectedSegments = new FragmentsInSelectedSegments(
			selectedSegments);

	for (int level = 0; level < thresholded.getDataSource().getNumMipmapLevels(); ++level)
	{
		final DataSource<D, T> labelsSource = labels.getDataSource() instanceof MaskedSource<?, ?>
		                                      ? ((MaskedSource<D, T>) labels.getDataSource()).underlyingSource()
		                                      : labels.getDataSource();
		final AffineTransform3D tf1 = new AffineTransform3D();
		final AffineTransform3D tf2 = new AffineTransform3D();
		thresholded.getDataSource().getSourceTransform(0, level, tf1);
		labelsSource.getSourceTransform(0, level, tf2);
		if (!Arrays.equals(tf1.getRowPackedCopy(), tf2.getRowPackedCopy()))
		{
			throw new RuntimeException("Incompatible sources ( transforms )");
		}

		final RandomAccessibleInterval<B> thresh = thresholded.getDataSource().getDataSource(0, level);
		final RandomAccessibleInterval<D> label  = labelsSource.getDataSource(0, level);

		final CellGrid grid = label instanceof AbstractCellImg<?, ?, ?, ?>
		                      ? ((AbstractCellImg<?, ?, ?, ?>) label).getCellGrid()
		                      : new CellGrid(
				                      Intervals.dimensionsAsLongArray(label),
				                      Arrays.stream(Intervals.dimensionsAsLongArray(label)).mapToInt(l -> (int) l)
						                      .toArray());

		final B extension = Util.getTypeFromInterval(thresh);
		extension.set(false);
		final LabelIntersectionCellLoader<D, B> loader = new LabelIntersectionCellLoader<>(
				label,
				Views.extendValue(thresh, extension),
				checkForType(labelsSource.getDataType(), fragmentsInSelectedSegments),
				BooleanType::get,
				extension::copy);

		LOG.debug("Making intersect for level={} with grid={}", level, grid);


		final LoadedCellCacheLoader<UnsignedByteType, VolatileByteArray> cacheLoader = LoadedCellCacheLoader.get(grid, loader, new UnsignedByteType(), AccessFlags.setOf(AccessFlags.VOLATILE));
		final Cache<Long, Cell<VolatileByteArray>> cache = new SoftRefLoaderCache<Long, Cell<VolatileByteArray>>().withLoader(cacheLoader);
		final CachedCellImg<UnsignedByteType, VolatileByteArray> img = new CachedCellImg<>(grid, new UnsignedByteType(), cache, new VolatileByteArray(1, true));
		// TODO cannot use VolatileViews because we need access to cache
		final TmpVolatileHelpers.RaiWithInvalidate<VolatileUnsignedByteType> vimg = TmpVolatileHelpers.createVolatileCachedCellImgWithInvalidate(
				img,
				queue,
				new CacheHints(LoadingStrategy.VOLATILE, priority, true));
		data[level] = img;
		vdata[level] = vimg.getRai();
		invalidate[level] = img.getCache();
		vinvalidate[level] = vimg.getInvalidate();
		transforms[level] = tf1;

	}

	return new RandomAccessibleIntervalDataSource<>(
			new ValueTriple<>(data, vdata, transforms),
			new InvalidateDelegates<>(Arrays.asList(new InvalidateDelegates<>(invalidate), new InvalidateDelegates<>(vinvalidate))),
			Interpolations.nearestNeighbor(),
			Interpolations.nearestNeighbor(),
			name
	);
}
 
Example 12
Source File: DefaultPValue.java    From imagej-ops with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void compute(final RandomAccessibleInterval<T> image1,
	final RandomAccessibleInterval<U> image2, PValueResult output)
{
	final int[] blockSize = blockSize(image1, psfSize);
	final RandomAccessibleInterval<T> trimmedImage1 = trim(image1, blockSize);
	final RandomAccessibleInterval<U> trimmedImage2 = trim(image2, blockSize);
	final T type1 = Util.getTypeFromInterval(image1);

	final double[] sampleDistribution = new double[nrRandomizations];
	final IterableInterval<T> iterableImage1 = Views.iterable(trimmedImage1);
	final IterableInterval<U> iterableImage2 = Views.iterable(trimmedImage2);
	
	// compute actual coloc value
	final double value = op.calculate(iterableImage1, iterableImage2);
	
	// compute shuffled coloc values in parallel
	int threadCount = Runtime.getRuntime().availableProcessors(); // FIXME: conform to Ops threading strategy...
	Random r = new Random(seed);
	long[] seeds = new long[nrRandomizations];
	for (int s = 0; s < nrRandomizations; s++ ) {
		seeds[s] = r.nextLong();
	}
	ArrayList<Future<?>> future = new ArrayList<>(threadCount);
	for (int t = 0; t < threadCount; t++) {
		int offset = t * nrRandomizations / threadCount;
		int count = (t+1) * nrRandomizations / threadCount - offset;
		future.add(ts.run(() -> {
			final ShuffledView<T> shuffled = new ShuffledView<>(trimmedImage1,
				blockSize, seeds[offset]); // a new one per thread and each needs its own seed
			Img<T> buffer = Util.getSuitableImgFactory(shuffled, type1).create(
				shuffled);
			for (int i = 0; i < count; i++) {
				int index = offset + i;
				if (index >= nrRandomizations) break;
				if (i > 0) shuffled.shuffleBlocks(seeds[index]);
				copy(shuffled, buffer);
				sampleDistribution[index] = op.calculate(buffer, iterableImage2);
			}
		}));
	}

	// wait for threads to finish
	try {
		for (int t = 0; t < threadCount; t++) {
			future.get(t).get();
		}
	}
	catch (final InterruptedException | ExecutionException exc) {
		final Throwable cause = exc.getCause();
		if (cause instanceof RuntimeException) throw (RuntimeException) cause;
		throw new RuntimeException(exc);
	}

	output.setColocValue(value);
	output.setColocValuesArray(sampleDistribution);
	output.setPValue(calculatePvalue(value, sampleDistribution));
}