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

The following examples show how to use net.imglib2.RandomAccessibleInterval#dimension() . 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: N5FragmentSegmentAssignmentInitialLut.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
@Override
public TLongLongMap get() {
	try {
		RandomAccessibleInterval<UnsignedLongType> data = openDatasetSafe(meta.reader(), meta.dataset());
		final long[] keys = new long[(int) data.dimension(0)];
		final long[] values = new long[keys.length];
		LOG.debug("Found {} assignments", keys.length);
		final Cursor<UnsignedLongType> keyCursor = Views.flatIterable(Views.hyperSlice(data, 1, 0L)).cursor();
		final Cursor<UnsignedLongType> valueCursor = Views.flatIterable(Views.hyperSlice(data, 1, 1L)).cursor();
		for (int i = 0; i < keys.length; ++i) {
			keys[i] = keyCursor.next().getIntegerLong();
			values[i] = valueCursor.next().getIntegerLong();
		}
		return new TLongLongHashMap(keys, values);
	} catch (IOException e) {
		LOG.debug("Exception while trying to return initial lut from N5", e);
		LOG.info("Unable to read initial lut from {} -- returning empty map", meta);
		return new TLongLongHashMap();
	}
}
 
Example 2
Source File: Align.java    From BigStitcher with GNU General Public License v2.0 6 votes vote down vote up
public Align(final RandomAccessibleInterval< T > template, final ImgFactory< FloatType > factory, WarpFunction model)
{
	this.template = template;

	n = template.numDimensions();
	warpFunction = model;
	numParameters = warpFunction.numParameters();
	
	currentTransform = new AffineTransform( n );
	
	final long[] dim = new long[n + 1];
	for ( int d = 0; d < n; ++d )
		dim[d] = template.dimension( d );
	dim[n] = n;
	final Img< FloatType > gradients = factory.create( dim, new FloatType() );
	gradients( Views.extendBorder( template ), gradients );

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

	Hinv = computeInverseHessian( descent );

	error = factory.create( template, new FloatType() );
}
 
Example 3
Source File: PhaseCorrelation2Util.java    From BigStitcher with GNU General Public License v2.0 5 votes vote down vote up
public static <T extends RealType<T>> RandomAccessible<T> extendImageByFactor(RandomAccessibleInterval<T> img, int [] extension)
{
	int[] extEachSide = new int[img.numDimensions()];
	for (int i = 0; i <img.numDimensions(); i++){
		extEachSide[i] = (int) (img.dimension(i) < extension[i] ? img.dimension(i) : extension[i]);	
	}
	return new BlendedExtendedMirroredRandomAccesible2<T>(img, extEachSide);
}
 
Example 4
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 5
Source File: Coloc_2.java    From Colocalisation_Analysis with GNU General Public License v3.0 5 votes vote down vote up
private RandomAccessibleInterval<T> project(
	final RandomAccessibleInterval<T> image)
{
	if (image.numDimensions() < 2) {
		throw new IllegalArgumentException("Dimensionality too small: " + //
			image.numDimensions());
	}

	final IterableInterval<T> input = Views.iterable(image);
	final T type = input.firstElement(); // e.g. unsigned 8-bit
	final long xLen = image.dimension(0);
	final long yLen = image.dimension(1);

	// initialize output image with minimum value of the pixel type
	final long[] outputDims = { xLen, yLen };
	final Img<T> output = new ArrayImgFactory<T>().create(outputDims, type);
	for (final T sample : output) {
		sample.setReal(type.getMinValue());
	}

	// loop over the input image, performing the max projection
	final Cursor<T> inPos = input.localizingCursor();
	final RandomAccess<T> outPos = output.randomAccess();
	while (inPos.hasNext()) {
		final T inPix = inPos.next();
		final long xPos = inPos.getLongPosition(0);
		final long yPos = inPos.getLongPosition(1);
		outPos.setPosition(xPos, 0);
		outPos.setPosition(yPos, 1);
		final T outPix = outPos.get();
		if (outPix.compareTo(inPix) < 0) {
			outPix.set(inPix);
		}
	}
	return output;
}
 
Example 6
Source File: DefaultDistanceTransformTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void generate4DImg(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++) {
			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 });
					raIn.get().set(random.nextBoolean());
				}
			}
		}
	}
}
 
Example 7
Source File: ShuffledView.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static <T> RandomAccessibleInterval<T> cropAtCenter(
	final RandomAccessibleInterval<T> image, final int[] blockSize)
{
	final long[] pos = new long[image.numDimensions()];
	for (int d = 0; d < pos.length; d++) {
		pos[d] = (image.dimension(d) % blockSize[d]) / 2;
	}
	return cropAt(image, blockSize, new Point(pos));
}
 
Example 8
Source File: ShuffledView.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private ShuffledView(final RandomAccessibleInterval<T> image,
	final int[] blockSize, final int[] blockIndices, final long seed)
{
	super(image); // uses same bounds as the input image
	this.image = image;
	this.blockSize = blockSize;

	// compute some info about our block sizes
	final int numDims = image.numDimensions();
	blockDims = new int[numDims];
	long totalBlocks = 1;
	for (int d = 0; d < numDims; d++) {
		final long blockDim = image.dimension(d) / blockSize[d];
		if (blockDim * blockSize[d] != image.dimension(d)) {
			throw new IllegalArgumentException("Image dimension #" + d +
				" is not evenly divisible by block size:" + blockSize[d] +
				"; Please call a ShuffledView.cropAt method to adjust the input.");
		}
		if (blockDim > Integer.MAX_VALUE) {
			throw new UnsupportedOperationException("Block dimension #" + d +
				" is too large: " + blockDim);
		}
		blockDims[d] = (int) blockDim;
		totalBlocks *= blockDims[d];
	}
	if (totalBlocks > Integer.MAX_VALUE) {
		throw new UnsupportedOperationException("Too many blocks: " +
			totalBlocks);
	}
	if (blockIndices == null) {
		this.blockIndices = new int[(int) totalBlocks];
		initializeBlocks();
		rng = new Random(seed);
		shuffleBlocks();
	}
	else {
		this.blockIndices = blockIndices;
	}
}
 
Example 9
Source File: Block.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
private static final void copy( final long start, final long loopSize, final RandomAccessible< FloatType > source, final RandomAccessibleInterval< FloatType > block, final long[] offset )
{
	final int numDimensions = source.numDimensions();
	final Cursor< FloatType > cursor = Views.iterable( block ).localizingCursor();

	// define where we will query the RandomAccess on the source
	// (we say it is the entire block, although it is just a part of it,
	// but which part depends on the underlying container)
	final long[] min = new long[ numDimensions ];
	final long[] max = new long[ numDimensions ];
	
	for ( int d = 0; d < numDimensions; ++d )
	{
		min[ d ] = offset[ d ];
		max[ d ] = offset[ d ] + block.dimension( d ) - 1;
	}

	final RandomAccess< FloatType > randomAccess = source.randomAccess( new FinalInterval( min, max ) );

	cursor.jumpFwd( start );

	final long[] tmp = new long[ numDimensions ];

	for ( long l = 0; l < loopSize; ++l )
	{
		cursor.fwd();
		cursor.localize( tmp );
		
		for ( int d = 0; d < numDimensions; ++d )
			tmp[ d ] += offset[ d ];
		
		randomAccess.setPosition( tmp );
		cursor.get().set( randomAccess.get() );
	}
}
 
Example 10
Source File: VolatileHierarchyProjectorPreMultiply.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
public VolatileHierarchyProjectorPreMultiply(
		final List<? extends RandomAccessible<A>> sources,
		final Converter<? super A, ARGBType> converter,
		final RandomAccessibleInterval<ARGBType> target,
		final RandomAccessibleInterval<ByteType> mask,
		final int numThreads,
		final ExecutorService executorService)
{
	super(Math.max(2, sources.get(0).numDimensions()), converter, target);

	this.sources.addAll(sources);
	numInvalidLevels = sources.size();

	this.mask = mask;

	iterableTarget = Views.iterable(target);

	target.min(min);
	target.max(max);
	sourceInterval = new FinalInterval(min, max);

	width = (int) target.dimension(0);
	height = (int) target.dimension(1);
	cr = -width;

	this.numThreads = numThreads;
	this.executorService = executorService;

	lastFrameRenderNanoTime = -1;
	clearMask();
}
 
Example 11
Source File: DistanceTransform2DCalibration.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Phase2Runnable2DCal(final double[][] tempValues, final RandomAccessibleInterval<T> raOut, final int xPos,
		final double[] calibration) {
	this.tempValues = tempValues;
	this.raOut = raOut;
	this.xPos = xPos;
	this.height = (int) raOut.dimension(1);
	this.calibration = calibration;
}
 
Example 12
Source File: RAIToPNGNotebookConverter.java    From scijava-jupyter-kernel with Apache License 2.0 5 votes vote down vote up
@Override
public PNGImageNotebookOutput convert(Object object) {

    RandomAccessibleInterval<T> source = (RandomAccessibleInterval<T>) object;

    // NB: Assume <=3 samples in the 3rd dimension means channels. Of course,
    // we have no metadata with a vanilla RAI, but this is a best guess;
    // 3rd dimensions with >3 samples are probably something like Z or time.
    final int cAxis = source.numDimensions() > 2 && source.dimension(2) <= 3 ? 2 : -1;

    String base64Image = (String) ijnb.RAIToPNG(source, 0, 1, cAxis, ValueScaling.AUTO);

    return new PNGImageNotebookOutput(base64Image);
}
 
Example 13
Source File: ProcessParalellPortionWeight.java    From SPIM_Registration with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String call() throws Exception 
{
	final int numViews = imgs.size();
	
	// make the interpolators, weights and get the transformations
	final ArrayList< RealRandomAccess< T > > interpolators = new ArrayList< RealRandomAccess< T > >( numViews );
	final ArrayList< RealRandomAccess< FloatType > > weightAccess = new ArrayList< RealRandomAccess< FloatType > >();
	final int[][] imgSizes = new int[ numViews ][ 3 ];
	
	for ( int i = 0; i < numViews; ++i )
	{
		final RandomAccessibleInterval< T > img = imgs.get( i );
		imgSizes[ i ] = new int[]{ (int)img.dimension( 0 ), (int)img.dimension( 1 ), (int)img.dimension( 2 ) };
		
		interpolators.add( Views.interpolate( Views.extendMirrorSingle( img ), interpolatorFactory ).realRandomAccess() );
					
		weightAccess.add( weights.get( i ).realRandomAccess() );
	}

	final Cursor< T > cursor = fusedImg.localizingCursor();
	final float[] s = new float[ 3 ];
	final float[] t = new float[ 3 ];
	
	cursor.jumpFwd( portion.getStartPosition() );
	
	for ( int j = 0; j < portion.getLoopSize(); ++j )
	{
		// move img cursor forward any get the value (saves one access)
		final T v = cursor.next();
		cursor.localize( s );
		
		if ( doDownSampling )
		{
			s[ 0 ] *= downSampling;
			s[ 1 ] *= downSampling;
			s[ 2 ] *= downSampling;
		}
		
		s[ 0 ] += bb.min( 0 );
		s[ 1 ] += bb.min( 1 );
		s[ 2 ] += bb.min( 2 );
		
		double sum = 0;
		double sumW = 0;
		
		for ( int i = 0; i < numViews; ++i )
		{				
			transforms[ i ].applyInverse( t, s );
			
			if ( FusionHelper.intersects( t[ 0 ], t[ 1 ], t[ 2 ], imgSizes[ i ][ 0 ], imgSizes[ i ][ 1 ], imgSizes[ i ][ 2 ] ) )
			{
				final RealRandomAccess< T > r = interpolators.get( i );
				r.setPosition( t );
				
				final RealRandomAccess< FloatType > weight = weightAccess.get( i );
				weight.setPosition( t );
				
				final double w = weight.get().get();
				
				sum += r.get().getRealDouble() * w;
				sumW += w;
			}
		}
		
		if ( sumW > 0 )
			v.setReal( sum / sumW );
	}
	
	return portion + " finished successfully (one weight).";
}
 
Example 14
Source File: FastFusionTools.java    From BigStitcher with GNU General Public License v2.0 4 votes vote down vote up
/**
 * apply blending to an image, save weights to separate image
 * @param image image to apply blending to
 * @param weightImage image to save weights to
 * @param renderOffset (subpixel) offset of the original image to the provided version
 * @param border blank pixels on each border
 * @param blending extent of blending on each border
 * @param multiplyWeights false: just set weightImage to new weights, true: multiply existing weightImage
 * @param pool thread pool
 * @param <T> image pixel data type
 * @param <R> weight image pixel data type
 */
public static <T extends RealType<T>, R extends RealType<R> > void applyWeights(
		final RandomAccessibleInterval< T > image,
		final RandomAccessibleInterval< R > weightImage,
		final float[] renderOffset,
		final float[] border, 
		final float[] blending,
		final boolean multiplyWeights,
		final ExecutorService pool)
{
	final int n = image.numDimensions();
	final int[] min = new int[n];
	final int[] dimMinus1 = new int[n];
	for (int d=0; d<n; d++)
	{
		min[d] = (int) image.min( d );
		dimMinus1[d] = (int) image.dimension( d ) - 1;
	}

	final Vector< ImagePortion > portions = FusionTools.divideIntoPortions(  Views.iterable( image ).size() );
	final ArrayList< Callable< Void > > calls = new ArrayList<>();
	for (final ImagePortion portion : portions)
	{
		calls.add( new Callable< Void >()
		{
			@Override
			public Void call() throws Exception
			{
				// NB: assuming equal iteration order here
				final Cursor< R > weightC = Views.iterable( weightImage ).localizingCursor();
				final Cursor<T> inC = Views.iterable( image ).localizingCursor();
				inC.jumpFwd( portion.getStartPosition() );
				weightC.jumpFwd( portion.getStartPosition() );
				final float[] position = new float[n];
				for (long i=0; i<portion.getLoopSize(); i++)
				{
					inC.fwd();
					weightC.fwd();
					inC.localize( position );
					for (int d=0; d<n; d++)
						position[d] -= renderOffset[d];
					final float w = BlendingTools.computeWeight( position, min, dimMinus1, border, blending, n );
					inC.get().setReal( inC.get().getRealFloat() * w);
					
					if (multiplyWeights)
					{
						weightC.get().setReal(weightC.get().getRealDouble() * w );
					}
					else
					{
						weightC.get().setReal( w );
					}
				}
				return null;
			}
		} );
	}

	try
	{
		final List< Future< Void > > futures = pool.invokeAll( calls );
		for (final Future< Void > f : futures)
			f.get();
	}
	catch ( InterruptedException | ExecutionException e ) { e.printStackTrace(); }
}
 
Example 15
Source File: RichardsonLucyC.java    From imagej-ops with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void compute(RandomAccessibleInterval<I> in,
	RandomAccessibleInterval<K> kernel, RandomAccessibleInterval<O> out)
{
	// create FFT input memory if needed
	if (getFFTInput() == null) {
		setFFTInput(getCreateOp().calculate(in));
	}

	// create FFT kernel memory if needed
	if (getFFTKernel() == null) {
		setFFTKernel(getCreateOp().calculate(in));
	}

	// if a starting point for the estimate was not passed in then create
	// estimate Img and use the input as the starting point
	if (raiExtendedEstimate == null) {

		raiExtendedEstimate = createOp.calculate(in);

		copyOp.compute(in, raiExtendedEstimate);
	}

	// create image for the reblurred
	raiExtendedReblurred = createOp.calculate(in);

	// perform fft of psf
	fftKernelOp.compute(kernel, getFFTKernel());

	// -- perform iterations --

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

		if (status != null) {
			status.showProgress(i, getMaxIterations());
		}

		// create reblurred by convolving kernel with estimate
		// NOTE: the FFT of the PSF of the kernel has been passed in as a
		// parameter. when the op was set up, and computed above, so we can use
		// compute
		convolverOp.compute(raiExtendedEstimate, this.raiExtendedReblurred);

		// compute correction factor
		rlCorrectionOp.compute(in, raiExtendedReblurred, raiExtendedReblurred);

		// perform update to calculate new estimate
		updateOp.compute(raiExtendedReblurred, raiExtendedEstimate);

		// apply post processing
		if (iterativePostProcessingOps != null) {
			for (UnaryInplaceOp<RandomAccessibleInterval<O>, RandomAccessibleInterval<O>> pp : iterativePostProcessingOps) {
				pp.mutate(raiExtendedEstimate);
			}
		}

		// accelerate the algorithm by taking a larger step
		if (getAccelerator() != null) {
			getAccelerator().mutate(raiExtendedEstimate);
		}
	}

	// -- copy crop padded back to original size

	final long[] start = new long[out.numDimensions()];
	final long[] end = new long[out.numDimensions()];

	for (int d = 0; d < out.numDimensions(); d++) {
		start[d] = 0;
		end[d] = start[d] + out.dimension(d) - 1;
	}

	copy2Op.compute(Views.interval(raiExtendedEstimate, new FinalInterval(start,
		end)), out);
}
 
Example 16
Source File: HistogramOfOrientedGradients2D.java    From imagej-ops with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void compute(RandomAccessibleInterval<T> in, RandomAccessibleInterval<T> out) {
	final RandomAccessible<FloatType> convertedIn = Converters.convert(Views.extendMirrorDouble(in),
			converterToFloat, new FloatType());

	// compute partial derivative for each dimension
	RandomAccessibleInterval<FloatType> derivative0 = createImgOp.calculate();
	RandomAccessibleInterval<FloatType> derivative1 = createImgOp.calculate();

	// case of grayscale image
	if (in.numDimensions() == 2) {
		PartialDerivative.gradientCentralDifference(convertedIn, derivative0, 0);
		PartialDerivative.gradientCentralDifference(convertedIn, derivative1, 1);
	}
	// case of color image
	else {
		List<RandomAccessibleInterval<FloatType>> listDerivs0 = new ArrayList<>();
		List<RandomAccessibleInterval<FloatType>> listDerivs1 = new ArrayList<>();
		for (int i = 0; i < in.dimension(2); i++) {
			final RandomAccessibleInterval<FloatType> deriv0 = createImgOp.calculate();
			final RandomAccessibleInterval<FloatType> deriv1 = createImgOp.calculate();
			PartialDerivative.gradientCentralDifference(
					Views.interval(convertedIn, new long[] { 0, 0, i }, new long[] { in.max(0), in.max(1), i }),
					deriv0, 0);
			PartialDerivative.gradientCentralDifference(
					Views.interval(convertedIn, new long[] { 0, 0, i }, new long[] { in.max(0), in.max(1), i }),
					deriv1, 1);
			listDerivs0.add(deriv0);
			listDerivs1.add(deriv1);
		}
		derivative0 = Converters.convert(Views.collapse(Views.stack(listDerivs0)), converterGetMax,
				new FloatType());
		derivative1 = Converters.convert(Views.collapse(Views.stack(listDerivs1)), converterGetMax,
				new FloatType());
	}
	final RandomAccessibleInterval<FloatType> finalderivative0 = derivative0;
	final RandomAccessibleInterval<FloatType> finalderivative1 = derivative1;

	// compute angles and magnitudes
	final RandomAccessibleInterval<FloatType> angles = createImgOp.calculate();
	final RandomAccessibleInterval<FloatType> magnitudes = createImgOp.calculate();

	final CursorBasedChunk chunkable = new CursorBasedChunk() {

		@Override
		public void execute(long startIndex, long stepSize, long numSteps) {
			final Cursor<FloatType> cursorAngles = Views.flatIterable(angles).localizingCursor();
			final Cursor<FloatType> cursorMagnitudes = Views.flatIterable(magnitudes).localizingCursor();
			final Cursor<FloatType> cursorDerivative0 = Views.flatIterable(finalderivative0).localizingCursor();
			final Cursor<FloatType> cursorDerivative1 = Views.flatIterable(finalderivative1).localizingCursor();

			setToStart(cursorAngles, startIndex);
			setToStart(cursorMagnitudes, startIndex);
			setToStart(cursorDerivative0, startIndex);
			setToStart(cursorDerivative1, startIndex);

			for (long i = 0; i < numSteps; i++) {
				final float x = cursorDerivative0.get().getRealFloat();
				final float y = cursorDerivative1.get().getRealFloat();
				cursorAngles.get().setReal(getAngle(x, y));
				cursorMagnitudes.get().setReal(getMagnitude(x, y));

				cursorAngles.jumpFwd(stepSize);
				cursorMagnitudes.jumpFwd(stepSize);
				cursorDerivative0.jumpFwd(stepSize);
				cursorDerivative1.jumpFwd(stepSize);
			}
		}
	};

	ops().thread().chunker(chunkable, Views.flatIterable(magnitudes).size());

	// stores each Thread to execute
	final List<Callable<Void>> listCallables = new ArrayList<>();

	// compute descriptor (default 3x3, i.e. 9 channels: one channel for
	// each bin)
	final RectangleShape shape = new RectangleShape(spanOfNeighborhood, false);
	final NeighborhoodsAccessible<FloatType> neighborHood = shape.neighborhoodsRandomAccessible(angles);

	for (int i = 0; i < in.dimension(0); i++) {
		listCallables.add(new ComputeDescriptor(Views.interval(convertedIn, in), i, angles.randomAccess(),
				magnitudes.randomAccess(), (RandomAccess<FloatType>) out.randomAccess(),
				neighborHood.randomAccess()));
	}

	try {
		es.invokeAll(listCallables);
	} catch (final InterruptedException e) {
		throw new RuntimeException(e);
	}

	listCallables.clear();
}
 
Example 17
Source File: DefaultTubeness.java    From imagej-ops with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void compute(final RandomAccessibleInterval<T> input,
	final IterableInterval<DoubleType> tubeness)
{
	cancelReason = null;

	final int numDimensions = input.numDimensions();
	// Sigmas in pixel units.
	final double[] sigmas = new double[numDimensions];
	for (int d = 0; d < sigmas.length; d++) {
		final double cal = d < calibration.length ? calibration[d] : 1;
		sigmas[d] = sigma / cal;
	}

	/*
	 * Hessian.
	 */

	// Get a suitable image factory.
	final long[] gradientDims = new long[numDimensions + 1];
	final long[] hessianDims = new long[numDimensions + 1];
	for (int d = 0; d < numDimensions; d++) {
		hessianDims[d] = input.dimension(d);
		gradientDims[d] = input.dimension(d);
	}
	hessianDims[numDimensions] = numDimensions * (numDimensions + 1) / 2;
	gradientDims[numDimensions] = numDimensions;
	final Dimensions hessianDimensions = FinalDimensions.wrap(hessianDims);
	final FinalDimensions gradientDimensions = FinalDimensions.wrap(
		gradientDims);
	final ImgFactory<DoubleType> factory = ops().create().imgFactory(
		hessianDimensions);
	final Img<DoubleType> hessian = factory.create(hessianDimensions,
		new DoubleType());
	final Img<DoubleType> gradient = factory.create(gradientDimensions,
		new DoubleType());
	final Img<DoubleType> gaussian = factory.create(input, new DoubleType());

	// Handle multithreading.
	final int nThreads = Runtime.getRuntime().availableProcessors();
	final ExecutorService es = threadService.getExecutorService();

	try {
		// Hessian calculation.
		HessianMatrix.calculateMatrix(Views.extendBorder(input), gaussian,
			gradient, hessian, new OutOfBoundsBorderFactory<>(), nThreads, es,
			sigma);

		statusService.showProgress(1, 3);
		if (isCanceled()) return;

		// Hessian eigenvalues.
		final RandomAccessibleInterval<DoubleType> evs = TensorEigenValues
			.calculateEigenValuesSymmetric(hessian, TensorEigenValues
				.createAppropriateResultImg(hessian, factory, new DoubleType()),
				nThreads, es);

		statusService.showProgress(2, 3);
		if (isCanceled()) return;

		final AbstractUnaryComputerOp<Iterable<DoubleType>, DoubleType> method;
		switch (numDimensions) {
			case 2:
				method = new Tubeness2D(sigma);
				break;
			case 3:
				method = new Tubeness3D(sigma);
				break;
			default:
				System.err.println("Cannot compute tubeness for " + numDimensions +
					"D images.");
				return;
		}
		ops().transform().project(tubeness, evs, method, numDimensions);

		statusService.showProgress(3, 3);

		return;
	}
	catch (final IncompatibleTypeException | InterruptedException
			| ExecutionException e)
	{
		e.printStackTrace();
		return;
	}
}
 
Example 18
Source File: ExtractPSF.java    From SPIM_Registration with GNU General Public License v2.0 4 votes vote down vote up
public static < S extends RealType< S > > Img< S > computeMaxProjection( final RandomAccessibleInterval< S > avgPSF, final ImgFactory< S > factory, int minDim )
{
	final long[] dimensions = new long[ avgPSF.numDimensions() ];
	avgPSF.dimensions( dimensions );
	
	if ( minDim < 0 )
	{
		long minSize = dimensions[ 0 ];
		minDim = 0;
		
		for ( int d = 0; d < dimensions.length; ++d )
		{
			if ( avgPSF.dimension( d ) < minSize )
			{
				minSize = avgPSF.dimension( d );
				minDim = d;
			}
		}
	}
	
	final long[] projDim = new long[ dimensions.length - 1 ];
	
	int dim = 0;
	long sizeProjection = 0;
	
	// the new dimensions
	for ( int d = 0; d < dimensions.length; ++d )
		if ( d != minDim )
			projDim[ dim++ ] = dimensions[ d ];
		else
			sizeProjection = dimensions[ d ];
	
	final Img< S > proj = factory.create( projDim, Views.iterable( avgPSF ).firstElement() );
	
	final RandomAccess< S > psfIterator = avgPSF.randomAccess();
	final Cursor< S > projIterator = proj.localizingCursor();
	
	final int[] tmp = new int[ avgPSF.numDimensions() ];
	
	while ( projIterator.hasNext() )
	{
		projIterator.fwd();

		dim = 0;
		for ( int d = 0; d < dimensions.length; ++d )
			if ( d != minDim )
				tmp[ d ] = projIterator.getIntPosition( dim++ );

		tmp[ minDim ] = -1;
		
		double maxValue = -Double.MAX_VALUE;
		
		psfIterator.setPosition( tmp );
		for ( int i = 0; i < sizeProjection; ++i )
		{
			psfIterator.fwd( minDim );
			final double value = psfIterator.get().getRealDouble();
			
			if ( value > maxValue )
				maxValue = value;
		}
		
		projIterator.get().setReal( maxValue );
	}
	
	return proj;
}
 
Example 19
Source File: MaskAndRoiTest.java    From Colocalisation_Analysis with GNU General Public License v3.0 4 votes vote down vote up
/**
 * This test makes sure that a mask that is based on a lower dimension
 * image has the correct dimensionality.
 */
@Test
public void irregularRoiDimensionTest() {
	// load a 3D test image
	RandomAccessibleInterval<UnsignedByteType> img = positiveCorrelationImageCh1;
	final long width = img.dimension(0);
	final long height = img.dimension(1);
	final long slices = img.dimension(2);
	final long[] dimImg = new long[ img.numDimensions() ];
	img.dimensions(dimImg);
	// create a random noise 2D image -- set roiWidh/roiSize accordingly
	RandomAccessibleInterval<UnsignedByteType> maskSlice =
		TestImageAccessor.produceSticksNoiseImage( (int) width, (int) height, 50, 2, 10);
	RandomAccessibleInterval<BitType> mask =
			MaskFactory.createMask(dimImg, maskSlice);
	final long[] dimMask = new long[ mask.numDimensions() ];
	mask.dimensions(dimMask);
	// check the dimensions of the mask
	org.junit.Assert.assertArrayEquals(dimImg, dimMask);
	// make sure the mask actually got the same content on every slice
	final double[] offset = new double[ mask.numDimensions() ];
	Arrays.fill(offset, 0);
	double[] size = new double[ mask.numDimensions() ];
	size[0] = width;
	size[1] = height;
	size[2] = 1;
	RandomAccess<BitType> maskCursor = mask.randomAccess();
	RectangleRegionOfInterest roi = new RectangleRegionOfInterest( offset, size);
	Cursor<BitType> firstSliceCursor = roi.getIterableIntervalOverROI(mask).cursor();
	
	final long[] pos = new long[ mask.numDimensions() ];
	while (firstSliceCursor.hasNext()) {
		firstSliceCursor.fwd();
		firstSliceCursor.localize(pos);
		BitType maskValue = firstSliceCursor.get();
		// go through all slices
		for (int i=1; i<slices; ++i) {
			pos[2] = i;
			maskCursor.setPosition(pos);
			// compare the values and assume they are the same
			int cmp = maskCursor.get().compareTo(maskValue);
			assertEquals(0, cmp);
		}
	}
}
 
Example 20
Source File: AbstractPadAndFFTFilter.java    From imagej-ops with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * create FFT memory, create FFT filter and run it
 */
@Override
public void compute(
	final RandomAccessibleInterval<I> input,
	final RandomAccessibleInterval<K> kernel,
	final RandomAccessibleInterval<O> output)
{

	//RandomAccessibleInterval<O> output = createOutput(input, kernel);

	final int numDimensions = input.numDimensions();

	// 1. Calculate desired extended size of the image

	final long[] paddedSize = new long[numDimensions];

	if (borderSize == null) {
		// if no border size was passed in, then extend based on kernel size
		for (int d = 0; d < numDimensions; ++d) {
			paddedSize[d] = (int) input.dimension(d) + (int) kernel.dimension(d) -
				1;
		}

	}
	else {
		// if borderSize was passed in
		for (int d = 0; d < numDimensions; ++d) {

			paddedSize[d] = Math.max(kernel.dimension(d) + 2 * borderSize[d], input
				.dimension(d) + 2 * borderSize[d]);
		}
	}

	RandomAccessibleInterval<I> paddedInput = padOp.calculate(input,
		new FinalDimensions(paddedSize));

	RandomAccessibleInterval<K> paddedKernel = padKernelOp.calculate(kernel,
		new FinalDimensions(paddedSize));

	RandomAccessibleInterval<C> fftInput = createOp.calculate(
		new FinalDimensions(paddedSize));

	RandomAccessibleInterval<C> fftKernel = createOp.calculate(
		new FinalDimensions(paddedSize));

	// TODO: in this case it is difficult to match the filter op in the
	// 'initialize' as we don't know the size yet, thus we can't create
	// memory
	// for the FFTs
	filter = createFilterComputer(paddedInput, paddedKernel, fftInput,
		fftKernel, output);

	filter.compute(paddedInput, paddedKernel, output);
}