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

The following examples show how to use net.imglib2.img.Img#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: ImagePlaneDemo.java    From sciview with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static ByteBuffer imgToByteBuffer(Img<UnsignedByteType> img) {
    int numBytes = (int) (img.dimension(0) * img.dimension(1) * 3);
    ByteBuffer bb = BufferUtils.allocateByte(numBytes);
    byte[] rgb = new byte[]{0, 0, 0};

    RandomAccess<UnsignedByteType> ra = img.randomAccess();

    long[] pos = new long[3];

    for( int y = 0; y < img.dimension(1); y++ ) {
        for( int x = 0; x < img.dimension(0); x++ ) {
            for( int c = 0; c < img.dimension(2) - 1; c++ ) {// hard coded dropping of alpha
                pos[0] = x; pos[1] = img.dimension(1) - y - 1; pos[2] = c;
                ra.setPosition(pos);
                rgb[c] = ra.get().getByte();
            }
            bb.put(rgb);
        }
    }
    bb.flip();

    return bb;
}
 
Example 2
Source File: ImgSaver.java    From scifio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * @return The number of planes in the provided {@link Img}.
 */
private int getPlaneCount(final Img<?> img) {
	// PlanarImg case
	if (PlanarImg.class.isAssignableFrom(img.getClass())) {
		final PlanarImg<?, ?> planarImg = (PlanarImg<?, ?>) img;
		return planarImg.numSlices();
	}
	// General case
	int count = 1;

	for (int d = 2; d < img.numDimensions(); d++) {
		count *= img.dimension(d);
	}

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

	Img<FloatType> hogTestImg = openFloatImg("HoG2DResult.tif");
	Img<FloatType> hogInputImg = openFloatImg("HoG2DInput.png");

	// use numOrientations = 9 and spanOfNeighborhood = 2 for test
	@SuppressWarnings("unchecked")
	RandomAccessibleInterval<FloatType> hogOp = (RandomAccessibleInterval<FloatType>) ops
			.run(HistogramOfOrientedGradients2D.class, null, hogInputImg, 9, 2);

	RandomAccess<FloatType> raOp = hogOp.randomAccess();
	RandomAccess<FloatType> raTest = hogTestImg.randomAccess();

	// check dimensions
	assertEquals(hogTestImg.numDimensions(), hogOp.numDimensions());
	assertEquals(hogTestImg.dimension(0), hogOp.dimension(0));
	assertEquals(hogTestImg.dimension(1), hogOp.dimension(1));
	assertEquals(hogTestImg.dimension(2), hogOp.dimension(2));

	// check pixel values
	for (int i = 0; i < hogTestImg.dimension(0); i++) {
		for (int j = 0; j < hogTestImg.dimension(1); j++) {
			for (int k = 0; k < hogTestImg.dimension(2); k++) {
				raTest.setPosition(new long[] { i, j, k });
				raOp.setPosition(new long[] { i, j, k });
				assertEquals("i=" + i + ", j=" + j + ", k=" + k,
					raTest.get().getRealFloat(), raOp.get().getRealFloat(), EPSILON);
			}
		}
	}
}
 
Example 4
Source File: Max_Project.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
public static FloatProcessor toProcessor( final Img< ? extends RealType< ? > > img )
{
	final FloatProcessor fp = new FloatProcessor( (int)img.dimension( 0 ), (int)img.dimension( 1 ) );
	final float[] array = (float[])fp.getPixels();

	final Cursor< ? extends RealType< ? > > c = img.cursor();
	
	for ( int i = 0; i < array.length; ++ i)
		array[ i ] = c.next().getRealFloat();

	return fp;
}
 
Example 5
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 6
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 7
Source File: OverlayFusion.java    From Stitching with GNU General Public License v2.0 4 votes vote down vote up
public static < T extends RealType< T > & NativeType< T > > ImagePlus createReRegisteredSeries( final T targetType, final ImagePlus imp, final ArrayList<InvertibleBoundable> models, final int dimensionality )
{
	final int numImages = imp.getNFrames();

	// the size of the new image
	final int[] size = new int[ dimensionality ];
	// the offset relative to the output image which starts with its local coordinates (0,0,0)
	final double[] offset = new double[ dimensionality ];

	final int[][] imgSizes = new int[ numImages ][ dimensionality ];
	
	for ( int i = 0; i < numImages; ++i )
	{
		imgSizes[ i ][ 0 ] = imp.getWidth();
		imgSizes[ i ][ 1 ] = imp.getHeight();
		if ( dimensionality == 3 )
			imgSizes[ i ][ 2 ] = imp.getNSlices();
	}
	
	// estimate the boundaries of the output image and the offset for fusion (negative coordinates after transform have to be shifted to 0,0,0)
	Fusion.estimateBounds( offset, size, imgSizes, models, dimensionality );
			
	// for output
	final ImgFactory< T > f = new ImagePlusImgFactory< T >();
	// the composite
	final ImageStack stack = new ImageStack( size[ 0 ], size[ 1 ] );

	for ( int t = 1; t <= numImages; ++t )
	{
		for ( int c = 1; c <= imp.getNChannels(); ++c )
		{
			final Img<T> out = f.create( size, targetType );
			final Img< FloatType > in = ImageJFunctions.convertFloat( Hyperstack_rearranger.getImageChunk( imp, c, t ) );

			fuseChannel( out, Views.interpolate( Views.extendZero( in ), new NLinearInterpolatorFactory< FloatType >() ), offset, models.get( t - 1 ) );

			try
			{
				final ImagePlus outImp = ((ImagePlusImg<?,?>)out).getImagePlus();
				for ( int z = 1; z <= out.dimension( 2 ); ++z )
					stack.addSlice( imp.getTitle(), outImp.getStack().getProcessor( z ) );
			} 
			catch (ImgLibException e) 
			{
				Log.error( "Output image has no ImageJ type: " + e );
			}				
		}
	}
	
	//convertXYZCT ...
	ImagePlus result = new ImagePlus( "registered " + imp.getTitle(), stack );
	
	// numchannels, z-slices, timepoints (but right now the order is still XYZCT)
	if ( dimensionality == 3 )
	{
		result.setDimensions( size[ 2 ], imp.getNChannels(), imp.getNFrames() );
		result = OverlayFusion.switchZCinXYCZT( result );
		return CompositeImageFixer.makeComposite( result, CompositeImage.COMPOSITE );
	}
	//Log.info( "ch: " + imp.getNChannels() );
	//Log.info( "slices: " + imp.getNSlices() );
	//Log.info( "frames: " + imp.getNFrames() );
	result.setDimensions( imp.getNChannels(), 1, imp.getNFrames() );
	
	if ( imp.getNChannels() > 1 )
		return CompositeImageFixer.makeComposite( result, CompositeImage.COMPOSITE );
	return result;
}
 
Example 8
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;
	}
	*/
}
 
Example 9
Source File: MVDeconvolution.java    From SPIM_Registration with GNU General Public License v2.0 4 votes vote down vote up
protected static Img< FloatType > loadInitialImage(
		final String fileName,
		final boolean checkNumbers,
		final float minValue,
		final Dimensions dimensions,
		final ImgFactory< FloatType > imageFactory )
{
	IOFunctions.println( "Loading image '" + fileName + "' as start for iteration." );

	final ImagePlus impPSI = LegacyStackImgLoaderIJ.open( new File( fileName ) );

	if ( impPSI == null )
	{
		IOFunctions.println( "Could not load image '" + fileName + "'." );
		return null;
	}

	final long[] dimPsi = impPSI.getStack().getSize() == 1 ? 
			new long[]{ impPSI.getWidth(), impPSI.getHeight() } : new long[]{ impPSI.getWidth(), impPSI.getHeight(), impPSI.getStack().getSize() };
	final Img< FloatType > psi = imageFactory.create( dimPsi, new FloatType() );
	LegacyStackImgLoaderIJ.imagePlus2ImgLib2Img( impPSI, psi, false );

	if ( psi == null )
	{
		IOFunctions.println( "Could not load image '" + fileName + "'." );
		return null;
	}
	else
	{
		boolean dimensionsMatch = true;

		final long dim[] = new long[ dimensions.numDimensions() ];

		for ( int d = 0; d < psi.numDimensions(); ++d )
		{
			if ( psi.dimension( d ) != dimensions.dimension( d ) )
				dimensionsMatch = false;

			dim[ d ] = dimensions.dimension( d );
		}

		if ( !dimensionsMatch )
		{
			IOFunctions.println(
					"Dimensions of '" + fileName + "' do not match: " +
					Util.printCoordinates( dimPsi ) + " != " + Util.printCoordinates( dim ) );
			return null;
		}

		if ( checkNumbers )
		{
			IOFunctions.println(
					"Checking values of '" + fileName + "' you can disable this check by setting " +
					"spim.process.fusion.deconvolution.MVDeconvolution.checkNumbers = false;" );

			boolean smaller = false;
			boolean hasZerosOrNeg = false;
			
			for ( final FloatType v : psi )
			{
				if ( v.get() < minValue )
					smaller = true;

				if ( v.get() <= 0 )
				{
					hasZerosOrNeg = true;
					v.set( minValue );
				}
			}

			if ( smaller )
				IOFunctions.println(
						"Some values '" + fileName + "' are smaller than the minimal value of " +
						minValue + ", this can lead to instabilities." );

			if ( hasZerosOrNeg )
				IOFunctions.println(
						"Some values '" + fileName + "' were smaller or equal to zero," +
						"they have been replaced with the min value of " + minValue );
		}
	}

	return psi;
}
 
Example 10
Source File: Mirror.java    From SPIM_Registration with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @param image - The {@link Img} to mirror
 * @param dimension - The axis to mirror (e.g. 0-&gt;x-Axis-&gt;horizontally, 1-&gt;y-axis-&gt;vertically)
 * @param numThreads - number of threads
 */
public static < T extends Type< T > > boolean mirror( final Img< T > image, final int dimension, final int numThreads )
{
	final int n = image.numDimensions();

	// divide the image into chunks
	final long imageSize = image.size();
	final Vector< ImagePortion > portions = FusionHelper.divideIntoPortions( imageSize, numThreads * 4 );

	final long maxMirror = image.dimension( dimension ) - 1;
	final long sizeMirrorH = image.dimension( dimension ) / 2;

	// set up executor service
	final ExecutorService taskExecutor = Executors.newFixedThreadPool( Threads.numThreads() );
	final ArrayList< Callable< Void > > tasks = new ArrayList< Callable< Void > >();

	for ( final ImagePortion portion : portions )
	{
		tasks.add( new Callable< Void >() 
		{
			@Override
			public Void call() throws Exception
			{
				final Cursor< T > cursorIn = image.localizingCursor();
				final RandomAccess< T > cursorOut = image.randomAccess();
				final T temp = image.firstElement().createVariable();
				final long[] position = new long[ n ];

				// set the cursorIn to right offset
				final long startPosition = portion.getStartPosition();
				final long loopSize = portion.getLoopSize();

				if ( startPosition > 0 )
					cursorIn.jumpFwd( startPosition );

				// iterate over all pixels, if they are above the middle switch them with their counterpart
				// from the other half in the respective dimension
				for ( long i = 0; i < loopSize; ++i )
				{
					cursorIn.fwd();
					cursorIn.localize( position );

					if ( position[ dimension ] <= sizeMirrorH )
					{
						// set the localizable to the correct mirroring position
						position[ dimension ] = maxMirror - position[ dimension ];
						cursorOut.setPosition( position );

						// do a triangle switching
						final T in = cursorIn.get();
						final T out = cursorOut.get();

						temp.set( in );
						in.set( out );
						out.set( temp );
					}
				}

				return null;
			}
		});
	}

	try
	{
		// invokeAll() returns when all tasks are complete
		taskExecutor.invokeAll( tasks );
	}
	catch ( final InterruptedException e )
	{
		IOFunctions.println( "Failed to compute downsampling: " + e );
		e.printStackTrace();
		return false;
	}

	taskExecutor.shutdown();

	return true;
}
 
Example 11
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;
}