Java Code Examples for net.imglib2.RandomAccess#fwd()

The following examples show how to use net.imglib2.RandomAccess#fwd() . 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: 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 2
Source File: AccessedBlocksRandomAccessible.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
public static void main(final String[] args)
{
	final long[] dimensions = {10, 7};
	final int[]  blockSize  = {5, 3};

	final ArrayImg<LongType, LongArray> dummy = ArrayImgs.longs(dimensions);

	final AccessedBlocksRandomAccessible<LongType> tracker = new AccessedBlocksRandomAccessible<>(
			dummy,
			new CellGrid(dimensions, blockSize)
	);

	System.out.println(Arrays.toString(tracker.listBlocks()));
	final RandomAccess<LongType> ra = tracker.randomAccess();
	System.out.println(Arrays.toString(tracker.listBlocks()));
	ra.get();
	System.out.println(Arrays.toString(tracker.listBlocks()));
	ra.move(4, 0);
	ra.get();
	System.out.println(Arrays.toString(tracker.listBlocks()));
	ra.fwd(0);
	ra.get();
	System.out.println(Arrays.toString(tracker.listBlocks()));
	ra.move(6, 1);
	ra.get();
	System.out.println(Arrays.toString(tracker.listBlocks()));

}
 
Example 3
Source File: Align.java    From BigStitcher with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Compute the inverse Hessian matrix from the the steepest descent images.
 * @param descent descent image
 * @param <T> pixel type
 * @return Hessian
 */
public static <T extends RealType< T >> double[][] computeInverseHessian(
		final RandomAccessibleInterval< T > descent)
{
	final int n = descent.numDimensions() - 1;
	final int numParameters = (int) descent.dimension( n );
	final long[] dim = new long[n + 1];
	descent.dimensions( dim );
	dim[n] = 1;
	final LocalizingIntervalIterator pos = new LocalizingIntervalIterator( dim );
	final RandomAccess< T > r = descent.randomAccess();
	final double[] deriv = new double[numParameters];
	final double[][] H = new double[numParameters][numParameters];
	while ( pos.hasNext() )
	{
		pos.fwd();
		r.setPosition( pos );
		for ( int p = 0; p < numParameters; ++p )
		{
			deriv[p] = r.get().getRealDouble();
			r.fwd( n );
		}
		for ( int i = 0; i < numParameters; ++i )
			for ( int j = 0; j < numParameters; ++j )
				H[i][j] += deriv[i] * deriv[j];
	}
	return new Matrix( H ).inverse().getArray();
}
 
Example 4
Source File: Block.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
private static final void copy3dArray( final int threadIdx, final int numThreads, final RandomAccessible< FloatType > source, final ArrayImg< FloatType, ? > block, final long[] offset )
{
	final int w = (int)block.dimension( 0 );
	final int h = (int)block.dimension( 1 );
	final int d = (int)block.dimension( 2 );

	final long offsetX = offset[ 0 ];
	final long offsetY = offset[ 1 ];
	final long offsetZ = offset[ 2 ];
	final float[] blockArray = ((FloatArray)block.update( null ) ).getCurrentStorageArray();

	// define where we will query the RandomAccess on the source
	final FinalInterval interval = new FinalInterval( new long[] { offsetX, offsetY, offsetZ }, new long[] { offsetX + w - 1, offsetY + h - 1, offsetZ + d - 1 } );
	final RandomAccess< FloatType > randomAccess = source.randomAccess( interval );

	final long[] tmp = new long[]{ offsetX, offsetY, 0 };

	for ( int z = threadIdx; z < d; z += numThreads )
	{
		tmp[ 2 ] = z + offsetZ;
		randomAccess.setPosition( tmp );

		int i = z * h * w;

		for ( int y = 0; y < h; ++y )
		{
			randomAccess.setPosition( offsetX, 0 );

			for ( int x = 0; x < w; ++x )
			{
				blockArray[ i++ ] = randomAccess.get().get();
				randomAccess.fwd( 0 );
			}

			randomAccess.move( -w, 0 );
			randomAccess.fwd( 1 );
		}
	}
}
 
Example 5
Source File: SimpleInterruptibleProjectorPreMultiply.java    From paintera with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Render the 2D target image by copying values from the source. Source can have more dimensions than the target.
 * Target coordinate <em>(x,y)</em> is copied from source coordinate <em>(x,y,0,...,0)</em>.
 *
 * @return true if rendering was completed (all target pixels written). false if rendering was interrupted.
 */
@Override
public boolean map()
{
	interrupted.set(false);

	final StopWatch stopWatch = new StopWatch();
	stopWatch.start();

	min[0] = target.min(0);
	min[1] = target.min(1);
	max[0] = target.max(0);
	max[1] = target.max(1);

	final long cr = -target.dimension(0);

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

	final boolean         createExecutor = executorService == null;
	final ExecutorService ex             = createExecutor
	                                       ? Executors.newFixedThreadPool(numThreads)
	                                       : executorService;
	final int             numTasks;
	if (numThreads > 1)
	{
		numTasks = Math.min(numThreads * 10, height);
	}
	else
		numTasks = 1;
	final double                    taskHeight = (double) height / numTasks;
	final ArrayList<Callable<Void>> tasks      = new ArrayList<>(numTasks);
	for (int taskNum = 0; taskNum < numTasks; ++taskNum)
	{
		final long myMinY   = min[1] + (int) (taskNum * taskHeight);
		final long myHeight = (taskNum == numTasks - 1
		                       ? height
		                       : (int) ((taskNum + 1) * taskHeight)) - myMinY - min[1];

		final Callable<Void> r = () -> {
			if (interrupted.get())
				return null;

			System.out.println("WTF!");
			final RandomAccess<A>        sourceRandomAccess = source.randomAccess(
					SimpleInterruptibleProjectorPreMultiply.this);
			final RandomAccess<ARGBType> targetRandomAccess = target.randomAccess(target);

			sourceRandomAccess.setPosition(min);
			sourceRandomAccess.setPosition(myMinY, 1);
			targetRandomAccess.setPosition(min[0], 0);
			targetRandomAccess.setPosition(myMinY, 1);
			for (int y = 0; y < myHeight; ++y)
			{
				if (interrupted.get())
					return null;
				for (int x = 0; x < width; ++x)
				{
					final ARGBType argb = targetRandomAccess.get();
					converter.convert(sourceRandomAccess.get(), argb);
					final int nonpre = argb.get();
					argb.set(PixelUtils.NonPretoPre(nonpre));
					sourceRandomAccess.fwd(0);
					targetRandomAccess.fwd(0);
				}
				sourceRandomAccess.move(cr, 0);
				targetRandomAccess.move(cr, 0);
				sourceRandomAccess.fwd(1);
				targetRandomAccess.fwd(1);
			}
			return null;
		};
		tasks.add(r);
	}
	try
	{
		ex.invokeAll(tasks);
	} catch (final InterruptedException e)
	{
		Thread.currentThread().interrupt();
	}
	if (createExecutor)
		ex.shutdown();

	lastFrameRenderNanoTime = stopWatch.nanoTime();

	return !interrupted.get();
}
 
Example 6
Source File: AveragedRandomAccessible.java    From BigStitcher with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void fwd( final int dim )
{
	for (final RandomAccess< T > r : RAs )
		r.fwd( dim );
}
 
Example 7
Source File: FourNeighborhoodExtrema.java    From BigStitcher with GNU General Public License v2.0 4 votes vote down vote up
public static < T extends RealType< T > > ArrayList< Pair< Localizable, Double > > findMax( final RandomAccessible< T > img, final Interval region, final int maxN )
	{
		final Cursor< T > c = Views.iterable( Views.interval( img, region ) ).localizingCursor();
		final RandomAccess< T > r = img.randomAccess();
		final int n = img.numDimensions();

		final ArrayList< Pair< Localizable, Double > > list = new ArrayList< Pair< Localizable, Double > >();

		for ( int i = 0; i < maxN; ++i )
			list.add( new ValuePair< Localizable, Double >( null, -Double.MAX_VALUE ) );

A:		while ( c.hasNext() )
		{
			final double type = c.next().getRealDouble();
			r.setPosition( c );

			for ( int d = 0; d < n; ++d )
			{
				r.fwd( d );
				if ( type < r.get().getRealDouble() )
					continue A;
	
				r.bck( d );
				r.bck( d );
				
				if ( type < r.get().getRealDouble() )
					continue A;

				r.fwd( d );
			}

			
			for ( int i = maxN - 1; i >= 0; --i )
			{
				if ( type < list.get( i ).getB() )
				{
					if ( i == maxN - 1 )
					{
						continue A;
					}
					else
					{
						list.add( i + 1, new ValuePair< Localizable, Double >( new Point( c ), type ) );
						list.remove( maxN );
						continue A;
					}
				}
			}

			list.add( 0, new ValuePair< Localizable, Double >( new Point( c ), type ) );
			list.remove( maxN );
		}

		// remove all null elements
		for ( int i = maxN -1; i >= 0; --i )
			if ( list.get( i ).getA() == null )
				list.remove(  i );

		return list;
	}
 
Example 8
Source File: Fusion.java    From Stitching with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Helper method to fuse all the positions of a given
 * {@link ClassifiedRegion}. Since we do not know the dimensionality of the
 * region, we recurse over each position of each dimension. The tail step of
 * each descent iterates over all the images (classes) of the given region,
 * fusing the pixel values at the current position of each associated image.
 * This final value is then set in the output.
 */
private void processTile(ClassifiedRegion r, int[] images, int depth,
	PixelFusion myFusion, ArrayList<InvertibleBoundable> transform,
	ArrayList<RealRandomAccess<? extends RealType<?>>> in,
	RandomAccess<T> out, double[][] inPos,
	int threadNumber, int[] count, long[] lastDraw, ImagePlus fusionImp)
	throws NoninvertibleModelException
{
	// NB: there are two process tile methods, one for in-memory fusion
	// and one for writing to disk. They are slightly different, but
	// if one is updated the other should be as well!
	if (depth < r.size()) {
		Interval d = r.get(depth);

		// The intervals of the given region define the bounds of
		// iteration
		// So we are recursively defining a nested iteration order to
		// cover each position of the region
		int start = d.min();
		int end = d.max();

		// If this is the dimension being split up for multi-threading we
		// need to update the iteration bounds.
		if (depth == loopDim[0]) {
			start += loopOffset;
			end = start + loopSize - 1;
		}

		out.setPosition(start, depth);

		// NB: can't make this loop inclusive since we don't want the out.fwd
		// call to go out of bounds, and we can't setPosition (-1) or we
		// get AIOOB exceptions. So we loop 1 time less than desired, then
		// do a straight read after the loop.
		for (int i = start; i < end; i++) {
			// Recurse to the next depth (dimension)
			processTile(r, images, depth + 1, myFusion, transform, in, out,
				inPos, threadNumber, count, lastDraw, fusionImp);
			// move forward
			out.fwd(depth);
		}

		// Need to read the final position.
		processTile(r, images, depth + 1, myFusion, transform, in, out,
			inPos, threadNumber, count, lastDraw, fusionImp);
		return;
	}

	// compute fusion for this position
	myFusion.clear();

	// Loop over the images in this region
	for (int d = 0; d < r.size(); d++) {
		final double value = out.getDoublePosition(d) + offset[d];

		for (int index = 0; index < images.length; index++) {
			// Get the positions for the current image
			inPos[images[index]][d] = value;
		}
	}

	// Get the value at each input position
	for (int index = 0; index < images.length; index++) {
		final int image = images[index];
		// Transform to get input position
		transform.get(image).applyInverseInPlace(inPos[image]);
		in.get(image).setPosition(inPos[image]);
		// fuse
		myFusion.addValue(in.get(image).get().getRealFloat(), image, inPos[image]);
	}

	// set value
	out.get().setReal(myFusion.getValue());

	// Display progress if on thread 0
	if (threadNumber == 0) {
		count[0]++;
		// just every 10000'th pixel
		if (count[0] % 10000 == 0) {
			lastDraw[0] = drawFusion(lastDraw[0], fusionImp);
			IJ.showProgress(count[0] / positionsPerThread);
		}
	}
}
 
Example 9
Source File: DefaultDetectRidges.java    From imagej-ops with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public List<? extends WritablePolyline> calculate(RandomAccessibleInterval<T> input) {

	double sigma = (width / (2 * Math.sqrt(3)));

	// generate the metadata images
	RidgeDetectionMetadata ridgeDetectionMetadata = new RidgeDetectionMetadata(input, sigma,
		lowerThreshold, higherThreshold);

	// retrieve the metadata images
	Img<DoubleType> p_values = ridgeDetectionMetadata.getPValues();
	Img<DoubleType> n_values = ridgeDetectionMetadata.getNValues();
	Img<DoubleType> gradients = ridgeDetectionMetadata.getGradients();

	// create RandomAccesses for the metadata images
	OutOfBoundsConstantValueFactory<DoubleType, RandomAccessibleInterval<DoubleType>> oscvf =
		new OutOfBoundsConstantValueFactory<>(new DoubleType(0));
	RandomAccess<DoubleType> pRA = oscvf.create(p_values);
	RandomAccess<DoubleType> nRA = oscvf.create(n_values);
	RandomAccess<DoubleType> gradientRA = oscvf.create(gradients);

	// create the output polyline list.
	List<DefaultWritablePolyline> lines = new ArrayList<>();

	// start at the point of greatest maximum absolute value
	gradientRA.setPosition(RidgeDetectionUtils.getMaxCoords(gradients, true));

	// loop through the maximum values of the image
	while (Math.abs(gradientRA.get().get()) > higherThreshold) {

		// create the List of points that will be used to make the polyline
		List<RealPoint> points = new ArrayList<>();

		// get all of the necessary metadata from the image.
		long[] eigenvectorPos = { gradientRA.getLongPosition(0), gradientRA
			.getLongPosition(1), 0 };

		// obtain the n-values
		nRA.setPosition(eigenvectorPos);
		double eigenx = nRA.get().getRealDouble();
		nRA.fwd(2);
		double eigeny = nRA.get().getRealDouble();

		// obtain the p-values
		pRA.setPosition(eigenvectorPos);
		double px = pRA.get().getRealDouble();
		pRA.fwd(2);
		double py = pRA.get().getRealDouble();

		// start the list by adding the current point, which is the most line-like
		// point on the polyline
		points.add(RidgeDetectionUtils.get2DRealPoint(gradientRA
			.getDoublePosition(0) + px, gradientRA.getDoublePosition(1) + py));

		// go in the direction to the left of the perpendicular value
		getNextPoint(gradientRA, pRA, nRA, points, RidgeDetectionUtils.getOctant(
			eigenx, eigeny), eigenx, eigeny, px, py);

		// flip the array list around so that we get one cohesive line
		gradientRA.setPosition(new long[] { eigenvectorPos[0],
			eigenvectorPos[1] });
		Collections.reverse(points);

		// go in the opposite direction as before.
		eigenx = -eigenx;
		eigeny = -eigeny;
		getNextPoint(gradientRA, pRA, nRA, points, RidgeDetectionUtils.getOctant(
			eigenx, eigeny), eigenx, eigeny, px, py);

		// set the value to 0 so that it is not reused.
		gradientRA.get().setReal(0);

		// turn the list of points into a polyline, add to output list. If the
		// list has fewer vertices than the parameter, then we do not report it.
		if (points.size() > ridgeLengthMin) {
			DefaultWritablePolyline pline = new DefaultWritablePolyline(points);
			lines.add(pline);
		}
		// find the next max absolute value
		gradientRA.setPosition(RidgeDetectionUtils.getMaxCoords(gradients, true));
	}

	return lines;
}
 
Example 10
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 11
Source File: RandomAccessConverter.java    From scifio with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Uses a cursor to populate the plane. This solution is general and works
 * regardless of container, but at the expense of performance both now and
 * later.
 */
@Override
public <T extends RealType<T>> void populatePlane(final Reader reader,
	final int imageIndex, final int planeIndex, final byte[] plane,
	final ImgPlus<T> img, final SCIFIOConfig config)
{
	final Metadata m = reader.getMetadata();

	final int pixelType = m.get(imageIndex).getPixelType();
	final boolean little = m.get(imageIndex).isLittleEndian();

	final long[] dimLengths = imgUtilService.getDimLengths(m, imageIndex,
		config);
	final long[] pos = new long[dimLengths.length];

	final int planeX = 0;
	final int planeY = 1;

	getPosition(m, imageIndex, planeIndex, pos);

	final int sX = (int) img.dimension(0);
	final int sY = (int) img.dimension(1);

	final RandomAccess<T> randomAccess = img.randomAccess();

	int index = 0;

	for (int y = 0; y < sY; ++y) {
		pos[planeX] = 0;
		pos[planeY] = y;

		randomAccess.setPosition(pos);

		for (int x = 1; x < sX; ++x) {
			randomAccess.get().setReal(imgUtilService.decodeWord(plane, index++,
				pixelType, little));
			randomAccess.fwd(planeX);
		}

		randomAccess.get().setReal(imgUtilService.decodeWord(plane, index++,
			pixelType, little));
	}
}