Java Code Examples for net.imglib2.img.Img#localizingCursor()

The following examples show how to use net.imglib2.img.Img#localizingCursor() . 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: BlendingRealRandomAccess.java    From BigStitcher with GNU General Public License v2.0 6 votes vote down vote up
public static void main( String[] args )
{
	new ImageJ();
	
	Img< FloatType > img = ArrayImgs.floats( 500, 500 );
	BlendingRealRandomAccess blend = new BlendingRealRandomAccess(
			img,
			new float[]{ 100, 0 },
			new float[]{ 12, 150 } );
	
	Cursor< FloatType > c = img.localizingCursor();
	
	while ( c.hasNext() )
	{
		c.fwd();
		blend.setPosition( c );
		c.get().setReal( blend.get().getRealFloat() );
	}
	
	ImageJFunctions.show( img );
}
 
Example 2
Source File: VolumeTimeseriesDemo.java    From sciview with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public Img<UnsignedByteType> hardCopy(RandomAccessibleInterval<UnsignedByteType> img) {
    Img<UnsignedByteType> out =
            ArrayImgs.unsignedBytes(
                    img.dimension(0),
                    img.dimension(1),
                    img.dimension(2),
                    img.dimension(3));
    RandomAccess<UnsignedByteType> imgAccess = img.randomAccess();

    Cursor<UnsignedByteType> outCur = out.localizingCursor();
    while( outCur.hasNext() ) {
        outCur.fwd();
        imgAccess.setPosition(outCur);
        outCur.get().set(imgAccess.get());
    }

    return out;
}
 
Example 3
Source File: MorphologyOpsTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testFillHoles1() {
	Img<BitType> result = ops.create().img(invertedImgWithFilledHoles);
	Img<BitType> inverted = ops.create().img(invertedImgWithFilledHoles);
	ops.image().invert(inverted, imgWithHoles);
	ops.morphology().fillHoles(result, inverted, new DiamondShape(1));

	Cursor<BitType> resultC = result.localizingCursor();
	RandomAccess<BitType> groundTruthRA = invertedImgWithFilledHoles.randomAccess();

	while (resultC.hasNext()) {
		boolean r = resultC.next().get();
		groundTruthRA.setPosition(resultC);
		assertEquals(groundTruthRA.get().get(), r);
	}
}
 
Example 4
Source File: InvertTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testDoubleTypeCustomInvert() {
	final Img<DoubleType> inDoubleType = generateDoubleArrayTestImg(true, 5, 5);
	final Img<DoubleType> outDoubleType = inDoubleType.factory().create(
		inDoubleType, new DoubleType());

	// set this array of doubles to be the pixel values.
	final double[] nums = new double[] { Double.MAX_VALUE, Double.MIN_VALUE, 1d,
		-1d, 0d, Double.MAX_VALUE + 1, -Double.MAX_VALUE - 1, Math.PI, Math.E,
		Math.sqrt(Math.PI), Math.pow(25, 25), 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,
		Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY,
		Double.NEGATIVE_INFINITY };
	final Cursor<DoubleType> c = inDoubleType.localizingCursor();
	for (final double i : nums) {
		c.next();
		c.get().set(i);
	}
	assertDefaultInvert(inDoubleType, outDoubleType);
	assertDefaultInvertMinMaxProvided(inDoubleType, outDoubleType,
		new DoubleType(437d), new DoubleType(8008d));
}
 
Example 5
Source File: InvertTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private <T extends RealType<T>> void defaultCompare(
	final Img<T> in, final Img<T> out, final T min, final T max)
{
	final Cursor<T> inAccess = in.localizingCursor();
	final RandomAccess<T> outAccess = out.randomAccess();
	while (inAccess.hasNext()) {
		final T inVal = inAccess.next();
		outAccess.setPosition(inAccess);
		final T outVal = outAccess.get();
		final double bigIn = inVal.getRealDouble();
		final double minMax = min.getRealDouble() + max.getRealDouble() - bigIn;
		final double bigOut = outVal.getRealDouble();
		final T minMaxType = outVal.createVariable();
		minMaxType.setReal(minMax);
		if (minMax <= outVal.getMinValue()) assertEquals(outVal.getMinValue(),
			bigOut, 0.00005);
		else if (minMax >= outVal.getMaxValue()) assertEquals(outVal
			.getMaxValue(), bigOut, 0.00005);
		else assertEquals(minMaxType, outVal);
	}
}
 
Example 6
Source File: InvertTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private <T extends IntegerType<T>> void
	assertIntegerInvert(final Img<T> in, final Img<T> out)
{

	final Op op = ops.op(Ops.Image.Invert.class, out, in);
	assertSame(InvertIIInteger.class, op.getClass());
	op.run();
	
	Cursor<T> inCursor = in.localizingCursor();
	Cursor<T> outCursor = out.localizingCursor();
	
	while(inCursor.hasNext()) {
		inCursor.fwd();
		outCursor.fwd();
	}
	
	integerCompare(in, out, null, null);
}
 
Example 7
Source File: Downsample.java    From SPIM_Registration with GNU General Public License v2.0 6 votes vote down vote up
public static void main( String[] args )
{
	final Img< FloatType > img;
	
	//img = OpenImg.open( "/Users/preibischs/Documents/Microscopy/SPIM/HisYFP-SPIM/img_Angle0.tif", new ArrayImgFactory< FloatType >() );
	img = new ArrayImgFactory< FloatType >().create( new long[]{ 515,  231, 15 }, new FloatType() );
	
	final Cursor< FloatType > c = img.localizingCursor();
	
	while ( c.hasNext() )
	{
		c.next().set( c.getIntPosition( 0 ) % 10 + c.getIntPosition( 1 ) % 13 + c.getIntPosition( 2 ) % 3 );
	}
	
	new ImageJ();
	ImageJFunctions.show( img );
	ImageJFunctions.show( simple2x( img, img.factory(), new boolean[]{ true, true, true } ) );
}
 
Example 8
Source File: WeightNormalizer.java    From SPIM_Registration with GNU General Public License v2.0 6 votes vote down vote up
public static void main( String[] args )
{
	new ImageJ();
	
	Img< FloatType > img = ArrayImgs.floats( 500, 500 );
	BlendingRealRandomAccess blend = new BlendingRealRandomAccess(
			img,
			new float[]{ 100, 0 },
			new float[]{ 12, 150 } );
	
	Cursor< FloatType > c = img.localizingCursor();
	
	while ( c.hasNext() )
	{
		c.fwd();
		blend.setPosition( c );
		c.get().setReal( blend.get().getRealFloat() );
	}
	
	ImageJFunctions.show( img );
}
 
Example 9
Source File: BlendingRealRandomAccess.java    From SPIM_Registration with GNU General Public License v2.0 6 votes vote down vote up
public static void main( String[] args )
{
	new ImageJ();
	
	Img< FloatType > img = ArrayImgs.floats( 500, 500 );
	BlendingRealRandomAccess blend = new BlendingRealRandomAccess(
			img,
			new float[]{ 100, 0 },
			new float[]{ 12, 150 } );
	
	Cursor< FloatType > c = img.localizingCursor();
	
	while ( c.hasNext() )
	{
		c.fwd();
		blend.setPosition( c );
		c.get().setReal( blend.get().getRealFloat() );
	}
	
	ImageJFunctions.show( img );
}
 
Example 10
Source File: Fusion.java    From Stitching with GNU General Public License v2.0 5 votes vote down vote up
public static void main( String[] args )
{
	new ImageJ();
	
	// test blending
	ImgFactory< FloatType > f = new ArrayImgFactory< FloatType >();
	Img< FloatType > img = f.create( new int[] { 400, 400 }, new FloatType() ); 
	
	Cursor< FloatType > c = img.localizingCursor();
	final int numDimensions = img.numDimensions();
	final double[] tmp = new double[ numDimensions ];
	
	// for blending
	final long[] dimensions = new long[ numDimensions ];
	img.dimensions( dimensions );
	final float percentScaling = 0.2f;
	final double[] border = new double[ numDimensions ];
				
	while ( c.hasNext() )
	{
		c.fwd();
		
		for ( int d = 0; d < numDimensions; ++d )
			tmp[ d ] = c.getFloatPosition( d );
		
		c.get().set( (float)BlendingPixelFusion.computeWeight( tmp, dimensions, border, percentScaling ) );
	}
	
	ImageJFunctions.show( img );
	Log.debug( "done" );
}
 
Example 11
Source File: DefaultPValue.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void copy(ShuffledView<T> shuffled, Img<T> buffer) {
	Cursor<T> cursor = buffer.localizingCursor();
	RandomAccess<T> ra = shuffled.randomAccess();
	while (cursor.hasNext()) {
		T v = cursor.next();
		ra.setPosition(cursor);
		v.set(ra.get());
	}
}
 
Example 12
Source File: DefaultDerivativeGaussTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void regressionTest() {
	final int width = 10;
	final Img<DoubleType> input = ops.convert().float64(
		generateFloatArrayTestImg(false, width, width));

	final Img<DoubleType> output = ops.create().img(input);

	// Draw a line on the image
	final RandomAccess<DoubleType> inputRA = input.randomAccess();
	inputRA.setPosition(5, 0);
	for (int i = 0; i < 10; i++) {
		inputRA.setPosition(i, 1);
		inputRA.get().set(255);
	}

	// filter the image
	final int[] derivatives = new int[] { 1, 0 };
	final double[] sigmas = new double[] { 0.5, 0.5 };
	ops.filter().derivativeGauss(output, input, derivatives, sigmas);

	final Cursor<DoubleType> cursor = output.localizingCursor();
	int currentPixel = 0;
	while (cursor.hasNext()) {
		cursor.fwd();
		assertEquals(cursor.get().getRealDouble(),
			regressionRowValues[currentPixel % width], 0);
		currentPixel++;
	}
}
 
Example 13
Source File: ContentBased.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
final private static Img< FloatType > createGaussianKernel( final double[] sigmas )
{
	final int numDimensions = sigmas.length;

	final long[] imageSize = new long[ numDimensions ];
	final double[][] kernel = new double[ numDimensions ][];

	for ( int d = 0; d < numDimensions; ++d )
	{
		kernel[ d ] = Util.createGaussianKernel1DDouble( sigmas[ d ], true );
		imageSize[ d ] = kernel[ d ].length;
	}

	final Img< FloatType > kernelImg = ArrayImgs.floats( imageSize );

	final Cursor< FloatType > cursor = kernelImg.localizingCursor();
	final int[] position = new int[ numDimensions ];

	while ( cursor.hasNext() )
	{
		cursor.fwd();
		cursor.localize( position );

		double value = 1;

		for ( int d = 0; d < numDimensions; ++d )
			value *= kernel[ d ][ position[ d ] ];

		cursor.get().set( ( float ) value );
	}

	return kernelImg;
}
 
Example 14
Source File: ExtractPSF.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Make image the same size as defined, center it
 * 
 * @param img
 * @return
 */
public static < T extends RealType< T > > Img< T > makeSameSize( final Img< T > img, final long[] sizeIn )
{
	final long[] size = sizeIn.clone();

	double min = Double.MAX_VALUE;

	for ( final T f : img )
		min = Math.min( min, f.getRealDouble() );

	final Img< T > square = img.factory().create( size, img.firstElement() );

	final Cursor< T > squareCursor = square.localizingCursor();
	final T minT = img.firstElement().createVariable();
	minT.setReal( min );

	final RandomAccess< T > inputCursor = Views.extendValue( img, minT ).randomAccess();

	while ( squareCursor.hasNext() )
	{
		squareCursor.fwd();
		squareCursor.localize( size );
		
		for ( int d = 0; d < img.numDimensions(); ++d )
			size[ d ] =  size[ d ] - square.dimension( d )/2 + img.dimension( d )/2;

		inputCursor.setPosition( size );
		squareCursor.get().set( inputCursor.get() );
	}
	
	return square;
}
 
Example 15
Source File: Coloc_2.java    From Colocalisation_Analysis with GNU General Public License v3.0 4 votes vote down vote up
/**
 * A method to get the bounding box from the data in the given image that is
 * above zero. Those values are interpreted as a mask. It will return null if
 * no mask information was found.
 *
 * @param mask The image to look for "on" values in
 * @return a new MaskInfo object or null
 */
protected MaskInfo getBoundingBoxOfMask(final Img<T> mask) {
	final Cursor<T> cursor = mask.localizingCursor();

	final int numMaskDims = mask.numDimensions();
	// the "off type" of the mask
	final T offType = mask.firstElement().createVariable();
	offType.setZero();
	// the corners of the bounding box
	final long[][] minMax = new long[2][];
	// indicates if mask data has been found
	boolean maskFound = false;
	// a container for temporary position information
	final long[] pos = new long[numMaskDims];
	// walk over the mask
	while (cursor.hasNext()) {
		cursor.fwd();
		final T data = cursor.get();
		// test if the current mask data represents on or off
		if (data.compareTo(offType) > 0) {
			// get current position
			cursor.localize(pos);
			if (!maskFound) {
				// we found mask data, first time
				maskFound = true;
				// init min and max with the current position
				minMax[0] = Arrays.copyOf(pos, numMaskDims);
				minMax[1] = Arrays.copyOf(pos, numMaskDims);
			}
			else {
				/* Is is at least second hit, compare if it
				 * has new "extreme" positions, i.e. does
				 * is make the BB bigger?
				 */
				for (int d = 0; d < numMaskDims; d++) {
					if (pos[d] < minMax[0][d]) {
						// is it smaller than min
						minMax[0][d] = pos[d];
					}
					else if (pos[d] > minMax[1][d]) {
						// is it larger than max
						minMax[1][d] = pos[d];
					}
				}
			}
		}
	}
	if (!maskFound) return null;

	// calculate size
	final long[] size = new long[numMaskDims];
	for (int d = 0; d < numMaskDims; d++)
		size[d] = minMax[1][d] - minMax[0][d] + 1;
	// create and add bounding box
	final BoundingBox bb = new BoundingBox(minMax[0], size);
	return new MaskInfo(bb, mask);
}
 
Example 16
Source File: ExtractPSF.java    From SPIM_Registration with GNU General Public License v2.0 4 votes vote down vote up
/**
 * compute the average psf in original calibration and after applying the transformations
 */
public Img< T > computeAverageTransformedPSF()
{
	final long[] maxSize = computeMaxDimTransformedPSF();
	
	final int numDimensions = maxSize.length;
	
	IJ.log( "maxSize: " + Util.printCoordinates( maxSize ) );

	Img< T > someImg = pointSpreadFunctions.values().iterator().next();
	Img< T > avgPSF = someImg.factory().create( maxSize, someImg.firstElement() );
	
	final long[] avgCenter = new long[ numDimensions ];
	for ( int d = 0; d < numDimensions; ++d )
		avgCenter[ d ] = avgPSF.dimension( d ) / 2;

	for ( final ViewId viewId : getViewIdsForPSFs() )
	{
		final Img< T > psf = pointSpreadFunctions.get( viewId );

		// works if the kernel is even
		final RandomAccess< T > avgCursor = Views.extendZero( avgPSF ).randomAccess();
		final Cursor< T > psfCursor = psf.localizingCursor();
		
		final long[] loc = new long[ numDimensions ];
		final long[] psfCenter = new long[ numDimensions ];		
		for ( int d = 0; d < numDimensions; ++d )
			psfCenter[ d ] = psf.dimension( d ) / 2;
		
		while ( psfCursor.hasNext() )
		{
			psfCursor.fwd();
			psfCursor.localize( loc );
			
			for ( int d = 0; d < numDimensions; ++d )
				loc[ d ] = psfCenter[ d ] - loc[ d ] + avgCenter[ d ];
			
			avgCursor.setPosition( loc );
			avgCursor.get().add( psfCursor.get() );				
		}
	}
	
	return avgPSF;
}
 
Example 17
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 18
Source File: InvertTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private <T extends IntegerType<T>> void
	integerCompare(final Img<T> in, final Img<T> out, final IntegerType<T> min,
		final IntegerType<T> max)
{

	// Get min/max for the output type.
	final BigInteger minOut = InvertIIInteger.minValue(out.firstElement())
		.getBigInteger();
	final BigInteger maxOut = InvertIIInteger.maxValue(out.firstElement())
		.getBigInteger();
	BigInteger minMax = BigInteger.ZERO;

	// min + max
	if (min == null && max == null) {
		minMax = InvertIIInteger.minValue(in.firstElement()).getBigInteger().add(
			InvertIIInteger.maxValue(in.firstElement()).getBigInteger());
	}
	else if (min == null || max == null) {
		fail("Internal coding error");
	}
	else {
		minMax = min.getBigInteger().add(max.getBigInteger());
	}

	final Cursor<T> inAccess = in.localizingCursor();
	final RandomAccess<T> outAccess = out.randomAccess();
	while (inAccess.hasNext()) {
		final T inVal = inAccess.next();
		outAccess.setPosition(inAccess);
		final T outVal = outAccess.get();
		final BigInteger bigIn = inVal.getBigInteger();
		final BigInteger bigOut = outVal.getBigInteger();
		final BigInteger calcOut = minMax.subtract(bigIn);
		if (calcOut.compareTo(minOut) <= 0) {
			assertEquals(minOut, bigOut);
		}
		else if (calcOut.compareTo(maxOut) >= 0) {
			assertEquals(maxOut, bigOut);
		}
		else {
			assertEquals(calcOut, bigOut);

		}
	}
}
 
Example 19
Source File: OverlayFusion.java    From Stitching with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Fuse one slice/volume (one channel)
 * 
 * @param output - same the type of the ImagePlus input
 * @param input - FloatType, because of Interpolation that needs to be done
 * @param transform - the transformation
 */
protected static <T extends RealType<T>> void fuseChannel( final Img<T> output, final RealRandomAccessible<FloatType> input, final double[] offset, final InvertibleCoordinateTransform transform )
{
	final int dims = output.numDimensions();
	long imageSize = output.dimension( 0 );
	
	for ( int d = 1; d < output.numDimensions(); ++d )
		imageSize *= output.dimension( d );

	// run multithreaded
	final AtomicInteger ai = new AtomicInteger(0);					
       final Thread[] threads = SimpleMultiThreading.newThreads();

       final Vector<Chunk> threadChunks = SimpleMultiThreading.divideIntoChunks( imageSize, threads.length );
       
       for (int ithread = 0; ithread < threads.length; ++ithread)
           threads[ithread] = new Thread(new Runnable()
           {
               @Override
               public void run()
               {
               	// Thread ID
               	final int myNumber = ai.getAndIncrement();
       
               	// get chunk of pixels to process
               	final Chunk myChunk = threadChunks.get( myNumber );
               	final long startPos = myChunk.getStartPosition();
               	final long loopSize = myChunk.getLoopSize();
               	
           		final Cursor<T> out = output.localizingCursor();
           		final RealRandomAccess<FloatType> in = input.realRandomAccess();
           		
           		final double[] tmp = new double[ input.numDimensions() ];
           		
           		try 
           		{
               		// move to the starting position of the current thread
           			out.jumpFwd( startPos );
           			
               		// do as many pixels as wanted by this thread
                       for ( long j = 0; j < loopSize; ++j )
                       {
           				out.fwd();
           				
           				for ( int d = 0; d < dims; ++d )
           					tmp[ d ] = out.getDoublePosition( d ) + offset[ d ];
           				
           				transform.applyInverseInPlace( tmp );
           	
           				in.setPosition( tmp );
           				out.get().setReal( in.get().get() );
           			}
           		} 
           		catch (NoninvertibleModelException e) 
           		{
           			Log.error( "Cannot invert model, qutting." );
           			return;
           		}

               }
           });
       
       SimpleMultiThreading.startAndJoin( threads );
	
       /*
	final LocalizableCursor<T> out = output.createLocalizableCursor();
	final Interpolator<FloatType> in = input.createInterpolator( factory );
	
	final float[] tmp = new float[ input.getNumDimensions() ];
	
	try 
	{
		while ( out.hasNext() )
		{
			out.fwd();
			
			for ( int d = 0; d < dims; ++d )
				tmp[ d ] = out.getPosition( d ) + offset[ d ];
			
			transform.applyInverseInPlace( tmp );

			in.setPosition( tmp );			
			out.getType().setReal( in.getType().get() );
		}
	} 
	catch (NoninvertibleModelException e) 
	{
		Log.error( "Cannot invert model, qutting." );
		return;
	}
	*/
}