Java Code Examples for net.imglib2.Cursor#hasNext()

The following examples show how to use net.imglib2.Cursor#hasNext() . 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 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 2
Source File: VectorAccelerator.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public double DotProduct(final Img<T> image1, final Img<T> image2) {
	final Cursor<T> cursorImage1 = image1.cursor();
	final Cursor<T> cursorImage2 = image2.cursor();

	double dotProduct = 0.0d;

	while (cursorImage1.hasNext()) {
		cursorImage1.fwd();
		cursorImage2.fwd();

		float val1 = cursorImage1.get().getRealFloat();
		float val2 = cursorImage2.get().getRealFloat();

		dotProduct += val1 * val2;
	}

	return dotProduct;
}
 
Example 3
Source File: SliceTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testNonZeroMinimumInterval() {

	Img<ByteType> img3D = ArrayImgs.bytes(50, 50, 3);
	IntervalView<ByteType> interval2D = Views.interval(img3D,
			new FinalInterval(new long[] { 25, 25, 2 }, new long[] { 35, 35, 2 }));
	final int[] xyAxis = new int[] { 0, 1 };

	// iterate through every slice, should return a single
	// RandomAccessibleInterval<?> from 25, 25, 2 to 35, 35, 2

	final SlicesII<ByteType> hyperSlices = new SlicesII<>(interval2D, xyAxis, true);
	final Cursor<RandomAccessibleInterval<ByteType>> c = hyperSlices.cursor();
	int i = 0;
	while (c.hasNext()) {
		c.next();
		i++;
	}

	assertEquals(1, i);
}
 
Example 4
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 5
Source File: LinearIntensityMap.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
final static protected < S extends RealType< S >, T extends RealType< T > > void mapComposite(
		final IterableInterval< RealComposite< S > > image,
		final IterableInterval< RealComposite< T > > coefficients )
{
	final Cursor< RealComposite< S > > cs = image.cursor();
	final Cursor< RealComposite< T > > ct = coefficients.cursor();

	while ( cs.hasNext() )
	{
		final RealComposite< S > c = cs.next();
		final RealComposite< T > t = ct.next();

		for ( final S s : c )
			s.setReal( s.getRealDouble() * t.get( 0 ).getRealDouble() + t.get( 1 ).getRealDouble() );
	}
}
 
Example 6
Source File: FFTTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected void assertRAIsEqual(final RandomAccessibleInterval<FloatType> rai1,
	final RandomAccessibleInterval<FloatType> rai2, final float delta)
{
	final IterableInterval<FloatType> rai1Iterator = Views.iterable(rai1);
	final IterableInterval<FloatType> rai2Iterator = Views.iterable(rai2);

	final Cursor<FloatType> c1 = rai1Iterator.cursor();
	final Cursor<FloatType> c2 = rai2Iterator.cursor();

	while (c1.hasNext()) {
		c1.fwd();
		c2.fwd();

		// assert that the inverse = the input within the error delta
		assertEquals(c1.get().getRealFloat(), c2.get().getRealFloat(), delta);
	}
}
 
Example 7
Source File: DefaultCentralMoment30.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void compute(final IterableInterval<I> input, final O output) {
	final double moment00 = moment00Func.calculate(input).getRealDouble();
	final double moment10 = moment10Func.calculate(input).getRealDouble();

	final double centerX = moment10 / moment00;

	double centralmoment30 = 0;

	final Cursor<I> it = input.localizingCursor();
	while (it.hasNext()) {
		it.fwd();
		final double x = it.getDoublePosition(0) - centerX;
		final double val = it.get().getRealDouble();

		centralmoment30 += val * x * x * x;
	}

	output.setReal(centralmoment30);
}
 
Example 8
Source File: RidgeDetectionUtils.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected static long[] getMaxCoords(
	RandomAccessibleInterval<DoubleType> input, boolean useAbsoluteValue)
{
	long[] dims = new long[input.numDimensions()];
	double max = Double.MIN_VALUE;
	Cursor<DoubleType> cursor = Views.iterable(input).localizingCursor();
	while (cursor.hasNext()) {
		cursor.fwd();
		double current = useAbsoluteValue ? Math.abs(cursor.get().get()) : cursor
			.get().get();
		if (current > max) {
			max = current;
			for (int d = 0; d < input.numDimensions(); d++) {
				dims[d] = cursor.getLongPosition(d);
			}
		}
	}
	return dims;
}
 
Example 9
Source File: GameOfLife3D.java    From sciview with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Randomizes a new bit field. */
public void randomize() {
    final Cursor<UnsignedByteType> cursor = field.localizingCursor();
    final double chance = saturation / 100d;
    while( cursor.hasNext() ) {
        final boolean alive = Math.random() <= chance;
        cursor.next().set( alive ? ALIVE : DEAD );
    }
    updateVolume();
}
 
Example 10
Source File: MaskFactory.java    From Colocalisation_Analysis with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a new mask image with a defined size and preset content.
 * @throws MissingPreconditionException
 */
public static RandomAccessibleInterval<BitType> createMask(long[] dim, long[] roiOffset, long[] roiDim)
		throws MissingPreconditionException {
	if (dim.length != roiOffset.length || dim.length != roiDim.length) {
		throw new MissingPreconditionException("The dimensions of the mask as well as the ROIs and his offset must be the same.");
	}

	final RandomAccessibleInterval<BitType> mask = createMask(dim);
	final int dims = mask.numDimensions();
	final long[] pos = new long[dims];
	

	// create an array with the max corner of the ROI
	final long[] roiOffsetMax = new long[dims];
	for (int i=0; i<dims; ++i)
		roiOffsetMax[i] = roiOffset[i] + roiDim[i];
	// go through the mask and mask points as valid that are in the ROI
	Cursor<BitType> cursor = Views.iterable(mask).localizingCursor();
	while ( cursor.hasNext() ) {
		cursor.fwd();
		cursor.localize(pos);
		boolean valid = true;
		// test if the current position is contained in the ROI
		for(int i=0; i<dims; ++i)
			valid &= pos[i] >= roiOffset[i] && pos[i] < roiOffsetMax[i];
		cursor.get().set(valid);
	}

	return mask;
}
 
Example 11
Source File: LegacySlideBook6ImgLoader.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
public static final < T extends RealType< T > > void readUnsignedInts( final byte[] b, final Cursor< T > cursor, final int width, final boolean isLittleEndian )
{
	while( cursor.hasNext() )
	{
		cursor.fwd();
		cursor.get().setReal( LegacyStackImgLoaderLOCI.getIntValue( b, ( cursor.getIntPosition( 0 ) + cursor.getIntPosition( 1 ) * width ) * 4, isLittleEndian ) );
	}
}
 
Example 12
Source File: ConvertIIsTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testCopy() {
	ops.run(ConvertIIs.class, out, in,
		new CopyRealTypes<ShortType, ByteType>());

	final Cursor<ShortType> c = in.localizingCursor();
	final RandomAccess<ByteType> ra = out.randomAccess();
	while (c.hasNext()) {
		final short value = c.next().get();
		ra.setPosition(c);
		assertEquals(copy(value), ra.get().get());
	}
}
 
Example 13
Source File: ColocImgLibGadgets.java    From Colocalisation_Analysis with GNU General Public License v3.0 5 votes vote down vote up
/**
  * To randomize blockwise we enumerate the blocks, shuffle that list and
  * write the data to their new position based on the shuffled list.
  */
 protected Img<T> generateRandomImageStack(Img<T> img, int[] blockDimensions) {
int numberOfDimensions = Math.min(img.numDimensions(), blockDimensions.length);
int numberOfBlocks = 0;
long[] numberOfBlocksPerDimension = new long[numberOfDimensions];

for (int i = 0 ; i<numberOfDimensions; i++){
	if (img.dimension(i) % blockDimensions[i] != 0){
		System.out.println("sorry, for now image dims must be divisable by block size");
		return null;
	}
	numberOfBlocksPerDimension[i] = img.dimension(i) / blockDimensions[i];
	numberOfBlocks *= numberOfBlocksPerDimension[i];
}
List<Integer> allTheBlocks = new ArrayList<Integer>(numberOfBlocks);
for (int i = 0; i<numberOfBlocks; i++){
	allTheBlocks.add(new Integer(i));
}
Collections.shuffle(allTheBlocks, new Random());
Cursor<T> cursor = img.cursor();

// create factories for new image stack
//ContainerFactory containerFactory = new ImagePlusContainerFactory();
ImgFactory<T> imgFactory = new ArrayImgFactory<T>();
//new ImageFactory<T>(cursor.getType(), containerFactory);

// create a new stack for the random images
final long[] dim = new long[ img.numDimensions() ];
img.dimensions(dim);
Img<T> randomStack = imgFactory.create(dim, img.firstElement().createVariable());

// iterate over image data
while (cursor.hasNext()) {
	cursor.fwd();
	T type = cursor.get();
	// type.getRealDouble();
}

return randomStack;
 }
 
Example 14
Source File: LegacySlideBook6ImgLoader.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
public static final < T extends RealType< T > > void readUnsignedShorts( final byte[] b, final Cursor< T > cursor, final int width, final boolean isLittleEndian )
{
	while( cursor.hasNext() )
	{
		cursor.fwd();
		cursor.get().setReal( LegacyStackImgLoaderLOCI.getShortValueInt( b, ( cursor.getIntPosition( 0 ) + cursor.getIntPosition( 1 ) * width ) * 2, isLittleEndian ) );
	}
}
 
Example 15
Source File: Maps.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static <I1, I2, O> void map(final IterableInterval<I1> a,
	final RandomAccessibleInterval<I2> b, final IterableInterval<O> c,
	final BinaryComputerOp<I1, I2, O> op)
{
	final Cursor<I1> aCursor = a.localizingCursor();
	final RandomAccess<I2> bAccess = b.randomAccess();
	final Cursor<O> cCursor = c.cursor();
	while (aCursor.hasNext()) {
		aCursor.fwd();
		bAccess.setPosition(aCursor);
		op.compute(aCursor.get(), bAccess.get(), cCursor.next());
	}
}
 
Example 16
Source File: MapViewTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testIterableIntervalView() {
	@SuppressWarnings("unchecked")
	final IterableInterval<ByteType> res =
		(IterableInterval<ByteType>) ops.run(MapViewIIToII.class, in, op,
			new ByteType());

	final Cursor<ByteType> iterable = res.cursor();
	while (iterable.hasNext()) {
		assertEquals((byte) 10, iterable.next().get());
	}
}
 
Example 17
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 18
Source File: MaskAndRoiTest.java    From Colocalisation_Analysis with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Tests if a masked walk over an image refers to the correct data
 * by copying the data to a separate image and then compare it with
 * the original image data. The position data in the original image
 * is calculated based on the ROI offset and the relative position
 * in the copied ROI image.
 * @throws MissingPreconditionException
 */
@Test
public void maskContentTest() throws MissingPreconditionException {
	// load a 3D test image
	final RandomAccessibleInterval<UnsignedByteType> img = positiveCorrelationImageCh1;
	final long[] roiOffset = createRoiOffset(img);
	final long[] roiSize = createRoiSize(img);
	final long[] dim = new long[ img.numDimensions() ];
	img.dimensions(dim);
	final RandomAccessibleInterval<BitType> mask =
			MaskFactory.createMask(dim, roiOffset, roiSize);

	// create cursor to walk an image with respect to a mask
	TwinCursor<UnsignedByteType> cursor = new TwinCursor<UnsignedByteType>(
			img.randomAccess(), img.randomAccess(),
			Views.iterable(mask).localizingCursor());

	// create an image for the "clipped ROI"
	ImgFactory<UnsignedByteType> maskFactory =
			new ArrayImgFactory<UnsignedByteType>();
	RandomAccessibleInterval<UnsignedByteType> clippedRoiImage =
			maskFactory.create( roiSize, new UnsignedByteType() ); //  "Clipped ROI" );
	RandomAccess<UnsignedByteType> outputCursor =
			clippedRoiImage.randomAccess();

	// copy ROI data to new image
	long[] pos = new long[ clippedRoiImage.numDimensions() ];
	while (cursor.hasNext()) {
		cursor.fwd();
		cursor.localize(pos);
		// shift position by offset
		for (int i=0; i<pos.length; i++) {
			pos[i] = pos[i] - roiOffset[i];
		}
		outputCursor.setPosition(pos);
		outputCursor.get().set( cursor.getFirst() );
	}

	/* go through the clipped ROI and compare the date to offset values
	 * of the original data.
	 */
	Cursor<UnsignedByteType> roiCopyCursor =
			Views.iterable(clippedRoiImage).localizingCursor();
	RandomAccess<UnsignedByteType> imgCursor =
			img.randomAccess();
	// create variable for summing up and set it to zero
	double sum = 0;
	pos = new long [ clippedRoiImage.numDimensions() ];
	while (roiCopyCursor.hasNext()) {
		roiCopyCursor.fwd();
		roiCopyCursor.localize(pos);
		// shift position by offset
		for (int i=0; i<pos.length; i++) {
			pos[i] = pos[i] + roiOffset[i];
		}
		// set position in original image
		imgCursor.setPosition(pos);
		// get ROI and original image data
		double roiData = roiCopyCursor.get().getRealDouble();
		double imgData = imgCursor.get().getRealDouble();
		// sum up the difference
		double diff = roiData - imgData;
		sum += diff * diff;
	}

	// check if sum is zero
	assertTrue("The sum of squared differences was " + sum + ".", Math.abs(sum) < 0.00001);
}
 
Example 19
Source File: MaskAndRoiTest.java    From Colocalisation_Analysis with GNU General Public License v3.0 4 votes vote down vote up
/**
 * This test test if a regular mask is created by the MaskFactory
 * correctly. First, the dimensions are checked, they must be the
 * same as the original images ones. Then it is checked if all
 * values in the mask image have the value they should have. For
 * a regular ROI this is easy to tell as one can calculate it out
 * of the position.
 */
@Test
public void regularMaskCreationTest() throws MissingPreconditionException {
	// load a 3D test image
	RandomAccessibleInterval<UnsignedByteType> img = positiveCorrelationImageCh1;
	final long[] roiOffset = createRoiOffset(img);
	final long[] roiSize = createRoiSize(img);
	final long[] dim = new long[ img.numDimensions() ];
	img.dimensions(dim);
	RandomAccessibleInterval<BitType> mask = MaskFactory.createMask(dim,
			roiOffset, roiSize);

	// is the number of dimensions the same as in the image?
	final long[] dimMask = new long[ mask.numDimensions() ];
	mask.dimensions(dimMask);
	assertTrue( Arrays.equals(dim, dimMask) );

	// go through the mask and check if all valid points are in the ROI
	long[] pos = new long[ img.numDimensions() ];
	final Cursor<BitType> cursor = Views.iterable(mask).localizingCursor();
	while ( cursor.hasNext() ) {
		cursor.fwd();
		cursor.localize(pos);
		// get values in mask image
		boolean onInMask = cursor.get().get();
		// calculate value that the current point *should* have
		boolean onInROI = true;
		for(int i=0; i<pos.length; ++i)
			onInROI &= pos[i] >= roiOffset[i] && pos[i] < (roiOffset[i] + roiSize[i]);
		// both values must match
		assertTrue(onInMask == onInROI);
	}

	/* go once more trough the image wrt. the mask to build a
	 * bounding box
	 */
	// create cursor to walk an image with respect to a mask
	final Predicate<BitType> predicate = new MaskPredicate();
	Cursor<BitType> roiCursor
		= new PredicateCursor<BitType>(
				Views.iterable(mask).localizingCursor(), predicate);
	long[] min = new long[ mask.numDimensions() ];
	long[] max = new long[ mask.numDimensions() ];
	Arrays.fill(min, Integer.MAX_VALUE);
	Arrays.fill(max, Integer.MIN_VALUE);
	while (roiCursor.hasNext()) {
		roiCursor.fwd();
		roiCursor.localize(pos);
		for (int i=0; i<pos.length; i++) {
			if (pos[i] < min[i])
				min[i] = pos[i];
			if (pos[i] > max[i])
				max[i] = pos[i];
		}
	}
	// the bounding box min should equal the ROI offset
	assertTrue(Arrays.equals(min, roiOffset));
	// create theoretical bounding box max and check it
	long[] roiMax = roiOffset.clone();
	for (int i=0; i<roiMax.length; i++)
		roiMax[i] += roiSize[i] - 1;
	assertTrue(Arrays.equals(max, roiMax));
}
 
Example 20
Source File: ExtractPSF.java    From SPIM_Registration with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 
 * @param filenames
 * @return
 */
public static < T extends RealType< T > & NativeType< T > > ExtractPSF< T > loadAndTransformPSFs(
		final ArrayList< Pair< Pair< Angle, Illumination >, String > > filenames,
		final ArrayList< ViewDescription > viewDesc,
		final T type,
		final HashMap< ViewId, AffineTransform3D > models )
{
	final ExtractPSF< T > extractPSF = new ExtractPSF< T >();

	for ( final ViewDescription vd : viewDesc )
	{
		final File file = getFileNameForViewId( vd, filenames );

		// extract the PSF for this one
		IOFunctions.println( "Loading PSF file '" + file.getAbsolutePath() );

		final ImagePlus imp = new Opener().openImage( file.getAbsolutePath() );

		if ( imp == null )
			throw new RuntimeException( "Could not load '" + file + "' using ImageJ (should be a TIFF file)." );

		final ImageStack stack = imp.getStack();
		final int width = imp.getWidth();
		final int sizeZ = imp.getNSlices();

		ArrayImg< T, ? > psfImage = new ArrayImgFactory< T >().create( new long[]{ width, imp.getHeight(), sizeZ }, type );

		for ( int z = 0; z < sizeZ; ++z )
		{
			final Cursor< T > cursor = Views.iterable( Views.hyperSlice( psfImage, 2, z ) ).localizingCursor();
			final ImageProcessor ip = stack.getProcessor( z + 1 );

			while ( cursor.hasNext() )
			{
				cursor.fwd();
				cursor.get().setReal( ip.getf( cursor.getIntPosition( 0 ) + cursor.getIntPosition( 1 ) * width ) );
			}
		}

		final ArrayImg< T, ? > psf;

		if ( models != null )
		{
			IOFunctions.println( "Transforming PSF for viewid " + vd.getViewSetupId() + ", file=" + file.getName() );
			psf = ExtractPSF.transformPSF( psfImage, models.get( vd ) );
		}
		else
		{
			IOFunctions.println( "PSF for viewid " + vd.getViewSetupId() + ", file=" + file.getName() + " will not be transformed." );
			psf = psfImage.copy();
		}

		extractPSF.viewIds.add( vd );
		extractPSF.pointSpreadFunctions.put( vd, psf );
		extractPSF.originalPSFs.put( vd, psfImage );
	}
	
	return extractPSF;
}