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

The following examples show how to use net.imglib2.img.Img#numDimensions() . 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: OutlineTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Test basic properties of the op's output */
@Test
public void testOutput() {
	// SETUP
	final long[] inputDims = { 3, 3, 3 };
	final Img<BitType> img = ArrayImgs.bits(inputDims);

	// EXECUTE
	final Img<BitType> result = (Img<BitType>) ops.morphology().outline(img,
		Boolean.TRUE);

	// VERIFY
	assertNotNull(result);
	final long[] outputDims = new long[result.numDimensions()];
	result.dimensions(outputDims);
	assertArrayEquals(inputDims, outputDims);
}
 
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: 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 4
Source File: FrangiVesselnessTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void regressionTest() throws Exception {

	// load in input image and expected output image.
	Img<FloatType> inputImg = (Img<FloatType>) ops.run(
		net.imagej.ops.image.equation.DefaultEquation.class,
		"Math.tan(0.3*p[0]) + Math.tan(0.1*p[1])");
	Img<FloatType> expectedOutput = ((Img<FloatType>) openFloatImg(
		"Result.tif"));

	// create ouput image
	long[] dims = new long[inputImg.numDimensions()];
	inputImg.dimensions(dims);
	Img<FloatType> actualOutput = ArrayImgs.floats(dims);

	// scale over which the filter operates (sensitivity)
	int scale = 1;

	// physical spacing between data points (1,1 since I got it from the
	// computer)
	double[] spacing = { 1, 1 };

	// run the op
	ops.run(net.imagej.ops.filter.vesselness.DefaultFrangi.class, actualOutput,
		inputImg, spacing, scale);

	// compare the output image data to that stored in the file.
	Cursor<FloatType> cursor = Views.iterable(actualOutput).localizingCursor();
	RandomAccess<FloatType> actualRA = actualOutput.randomAccess();
	RandomAccess<FloatType> expectedRA = expectedOutput.randomAccess();

	while (cursor.hasNext()) {
		cursor.fwd();
		actualRA.setPosition(cursor);
		expectedRA.setPosition(cursor);
		assertEquals(expectedRA.get().get(), actualRA.get().get(), 0);
	}
}
 
Example 5
Source File: FFTTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * utility that places a sphere in the center of the image
 * 
 * @param img
 */
private void placeSphereInCenter(final Img<FloatType> img) {

	final Point center = new Point(img.numDimensions());

	for (int d = 0; d < img.numDimensions(); d++)
		center.setPosition(img.dimension(d) / 2, d);

	final HyperSphere<FloatType> hyperSphere = new HyperSphere<>(img, center,
		2);

	for (final FloatType value : hyperSphere) {
		value.setReal(1);
	}
}
 
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
/**
 * 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 8
Source File: FourNeighborhoodExtremaTest.java    From BigStitcher with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testRandomPeaksMT()
{
	Img< FloatType > img = ArrayImgs.floats( 50, 50 );
	Random rnd = new Random( seed );
	
	for( FloatType t : img )
		t.set( rnd.nextFloat() );
	
	ArrayList< Pair< Localizable, Double > > correct = new ArrayList< Pair<Localizable,Double> >(); 
	
	RandomAccess<FloatType> ra = img.randomAccess();
	
	for ( int i = 0; i < 10; ++i ){
		for (int d = 0; d< img.numDimensions(); d++){
			ra.setPosition((int) (rnd.nextDouble() * 50), d);
		}
		ra.get().set((float) (rnd.nextDouble() + 1.0));
		
		correct.add(new ValuePair<Localizable, Double>(new Point(ra), new Double(ra.get().get())));
	}
	
	// sort the peaks in descending order
	Collections.sort(correct, new Comparator<Pair< Localizable, Double >>() {
		@Override
		public int compare(Pair<Localizable, Double> o1, Pair<Localizable, Double> o2) {
			return Double.compare(o2.getB(), o1.getB());
		}
	});
	
	int nMax = 5;
	ArrayList< Pair< Localizable, Double > > found = FourNeighborhoodExtrema.findMaxMT(Views.extendPeriodic(img), img, nMax, Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()));
	assertEquals(nMax, found.size());
	
	
	long[] posCorrect = new long[img.numDimensions()];
	long[] posFound = new long[img.numDimensions()];
	
	for (int i = 0; i<found.size(); i++){			
		assertEquals(correct.get(i).getB(), found.get(i).getB());
		
		correct.get(i).getA().localize(posCorrect);
		found.get(i).getA().localize(posFound);			
		assertArrayEquals(posCorrect, posFound);
	}
}
 
Example 9
Source File: Fusion.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 fuseBlockNoOverlap( final Img<T> output, final ArrayList< ? extends ImageInterpolation< ? extends RealType< ? > > > input, final double[] offset, 
		final ArrayList< InvertibleBoundable > transform, final boolean displayFusion )
{
	final int numDimensions = output.numDimensions();
	final int numImages = input.size();
			
	// run multithreaded
	final AtomicInteger ai = new AtomicInteger(0);					
       final Thread[] threads = SimpleMultiThreading.newThreads( numImages );
       
       for (int ithread = 0; ithread < threads.length; ++ithread)
           threads[ithread] = new Thread( new Runnable()
           {
               @Override
               public void run()
               {
               	// Thread ID
               	final int myImage = ai.getAndIncrement();
               	
               	// only the first thread does preview and update the status bar
               	// this requires no synchronized stuff
           		long lastDraw = 0;
           		ImagePlus fusionImp = null;

               	if ( displayFusion && myImage == 0 )
               	{
               		try
           			{
           				fusionImp = ((ImagePlusImg<?, ?>) output).getImagePlus();
           				fusionImp.setTitle( "fusing..." );
           				fusionImp.show();
           			}
           			catch ( ImgLibException e )
           			{
           				Log.error( "Output image has no ImageJ type: " + e );
           			}                		
               	}

               	final Img< ? extends RealType<?> > image = input.get( myImage ).getImg();
               	final int[] translation = new int[ numDimensions ];
               	
               	final InvertibleBoundable t = transform.get( myImage );
           		final double[] tmp = new double[ numDimensions ];
           		t.applyInPlace( tmp );

           		for ( int d = 0; d < numDimensions; ++d )
           			translation[ d ] = (int) Math.round( tmp[ d ] );

           		final Cursor< ? extends RealType<?> > cursor = image.localizingCursor();
           		final RandomAccess< ? extends RealType<?> > randomAccess = output.randomAccess();
           		final int[] pos = new int[ numDimensions ];
           		
           		int j = 0;
           		while ( cursor.hasNext() )
           		{
           			cursor.fwd();
           			cursor.localize( pos );
           			
       				// just thread 0
       				if ( myImage == 0 )
       				{
       					// just every 10000'th pixel
       					if ( j++ % 10000 == 0 )
       					{
               				lastDraw = drawFusion( lastDraw, fusionImp );
       						IJ.showProgress( (double)j / (double)image.size() );
       					}
       				}
         				
               		for ( int d = 0; d < numDimensions; ++d )
               		{
               			pos[ d ] += translation[ d ];
               			pos[ d ] -= offset[ d ];
               		}
               		
               		randomAccess.setPosition( pos );
               		randomAccess.get().setReal( cursor.get().getRealFloat() );
           		}
           		
   				if ( fusionImp != null )
   					fusionImp.hide();
                }
           });
       
       SimpleMultiThreading.startAndJoin( threads );        
}
 
Example 10
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 11
Source File: ConvolveTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/** tests fft based convolve */
@Test
public void testCreateAndConvolvePoints() {

	final int xSize = 128;
	final int ySize = 128;
	final int zSize = 128;

	int[] size = new int[] { xSize, ySize, zSize };

	Img<DoubleType> phantom = ops.create().img(size);

	RandomAccess<DoubleType> randomAccess = phantom.randomAccess();

	randomAccess.setPosition(new long[] { xSize / 2, ySize / 2, zSize / 2 });
	randomAccess.get().setReal(255.0);

	randomAccess.setPosition(new long[] { xSize / 4, ySize / 4, zSize / 4 });
	randomAccess.get().setReal(255.0);

	Point location = new Point(phantom.numDimensions());
	location.setPosition(new long[] { 3 * xSize / 4, 3 * ySize / 4, 3 * zSize /
		4 });

	HyperSphere<DoubleType> hyperSphere = new HyperSphere<>(phantom, location,
		5);

	for (DoubleType value : hyperSphere) {
		value.setReal(16);
	}

	// create psf using the gaussian kernel op (alternatively PSF could be an
	// input to the script)
	RandomAccessibleInterval<DoubleType> psf = ops.create().kernelGauss(
		new double[] { 5, 5, 5 }, new DoubleType());

	RandomAccessibleInterval<DoubleType> convolved = ops.create().img(size);

	// convolve psf with phantom
	convolved = ops.filter().convolve(convolved, phantom, psf);

	DoubleType sum = new DoubleType();
	DoubleType max = new DoubleType();
	DoubleType min = new DoubleType();

	ops.stats().sum(sum, Views.iterable(convolved));
	ops.stats().max(max, Views.iterable(convolved));
	ops.stats().min(min, Views.iterable(convolved));

	assertEquals(sum.getRealDouble(), 8750.000184601617, 0.0);
	assertEquals(max.getRealDouble(), 3.154534101486206, 0.0);
	assertEquals(min.getRealDouble(), -2.9776862220387557E-7, 0.0);
}
 
Example 12
Source File: MinFilterThreshold.java    From SPIM_Registration with GNU General Public License v2.0 4 votes vote down vote up
public boolean run()
{
	// fuse the dataset
	final ProcessFusion process;

	if ( loadSequentially )
		process = new ProcessSequential( spimData, viewIdsToProcess, bb, false, false, 1 );
	else
		process = new ProcessParalell( spimData, viewIdsToProcess, bb, false, false );

	Img< FloatType > img = process.fuseStack( new FloatType(), new NearestNeighborInterpolatorFactory<FloatType>(), timepoint, channel );

	final float[] minmax = FusionHelper.minMax( img );
	final int effR = Math.max( radiusMin / bb.getDownSampling(), 1 );
	final double threshold = (minmax[ 1 ] - minmax[ 0 ]) * ( background / 100.0 ) + minmax[ 0 ];

	IOFunctions.println( "Fused image minimum: " + minmax[ 0 ] );
	IOFunctions.println( "Fused image maximum: " + minmax[ 1 ] );
	IOFunctions.println( "Threshold: " + threshold );

	IOFunctions.println( "Computing minimum filter with effective radius of " + effR + " (downsampling=" + bb.getDownSampling() + ")" );

	img = computeLazyMinFilter( img, effR );

	if ( displaySegmentationImage )
		ImageJFunctions.show( img );

	this.min = new int[ img.numDimensions() ];
	this.max = new int[ img.numDimensions() ];

	if ( !computeBoundingBox( img, threshold, min, max ) )
		return false;

	IOFunctions.println( "Bounding box dim scaled: [" + Util.printCoordinates( min ) + "] >> [" + Util.printCoordinates( max ) + "]" );

	// adjust bounding box for downsampling and global coordinates
	for ( int d = 0; d < img.numDimensions(); ++d )
	{
		// downsampling
		min[ d ] *= bb.getDownSampling();
		max[ d ] *= bb.getDownSampling();
		
		// global coordinates
		min[ d ] += bb.min( d );
		max[ d ] += bb.min( d );
		
		// effect of the min filter + extra space
		min[ d ] -= radiusMin * 3;
		max[ d ] += radiusMin * 3;
	}
	
	IOFunctions.println( "Bounding box dim global: [" + Util.printCoordinates( min ) + "] >> [" + Util.printCoordinates( max ) + "]" );
	
	return true;
}
 
Example 13
Source File: MinFilterThreshold.java    From SPIM_Registration with GNU General Public License v2.0 4 votes vote down vote up
/**
 * By lazy I mean I was lazy to use a second image, one could of course implement it
 * on a n-d line by line basis @TODO
 * 
 * @param tmp1 - input image (overwritten, not necessarily the result, depends if number of dimensions is even or odd)
 * @param radius - the integer radius of the min filter
 */
final public static < T extends RealType< T > > Img< T > computeLazyMinFilter( final Img< T > tmp1, final int radius )
{
	final int n = tmp1.numDimensions();
	final int filterExtent = radius*2 + 1;
	final Img< T > tmp2 = tmp1.factory().create( tmp1, tmp1.firstElement() );
	
	// split up into many parts for multithreading
	final Vector< ImagePortion > portions = FusionHelper.divideIntoPortions( tmp1.size(), Threads.numThreads() * 2 );

	// set up executor service
	final ExecutorService taskExecutor = Executors.newFixedThreadPool( Threads.numThreads() );

	for ( int dim = 0; dim < n; ++dim )
	{
		final int d = dim;
		
		final RandomAccessible< T > input;
		final Img< T > output;
		
		if ( d % 2 == 0 )
		{
			input = Views.extendZero( tmp1 );
			output = tmp2;
		}
		else
		{
			input = Views.extendZero( tmp2 );
			output = tmp1;
		}
		
		final ArrayList< Callable< String > > tasks = new ArrayList< Callable< String > >();

		for ( final ImagePortion portion : portions )
		{
			tasks.add( new Callable< String >() 
					{
						@Override
						public String call() throws Exception
						{
							final RandomAccess< T > r = input.randomAccess();
							final int[] tmp = new int[ n ];

							final Cursor< T > c = output.localizingCursor();
							c.jumpFwd( portion.getStartPosition() );
							
							for ( long j = 0; j < portion.getLoopSize(); ++j )
							{
								final T t = c.next();
								c.localize( tmp );
								tmp[ d ] -= radius;
								r.setPosition( tmp );
								
								float min = Float.MAX_VALUE;
								
								for ( int i = 0; i < filterExtent; ++i )
								{
									min = Math.min( min, r.get().getRealFloat() );
									r.fwd( d );
								}
								
								t.setReal( min );
							}
							return "";
						}
					});
		}
		
		try
		{
			// invokeAll() returns when all tasks are complete
			taskExecutor.invokeAll( tasks );
		}
		catch ( final InterruptedException e )
		{
			IOFunctions.println( "Failed to compute lazy min filter: " + e );
			e.printStackTrace();
			return null;
		}
	}
	
	taskExecutor.shutdown();

	if ( n % 2 == 0 )
		return tmp1;
	else
		return tmp2;
}
 
Example 14
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 15
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 16
Source File: DeconvolveTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 3 votes vote down vote up
private void placeSphereInCenter(Img<FloatType> img) {

		final Point center = new Point(img.numDimensions());

		for (int d = 0; d < img.numDimensions(); d++)
			center.setPosition(img.dimension(d) / 2, d);

		HyperSphere<FloatType> hyperSphere = new HyperSphere<>(img, center, 30);

		for (final FloatType value : hyperSphere) {
			value.setReal(1);
		}
	}
 
Example 17
Source File: ConvolveTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 3 votes vote down vote up
private void placeSphereInCenter(Img<FloatType> img) {

		final Point center = new Point(img.numDimensions());

		for (int d = 0; d < img.numDimensions(); d++)
			center.setPosition(img.dimension(d) / 2, d);

		HyperSphere<FloatType> hyperSphere = new HyperSphere<>(img, center, 2);

		for (final FloatType value : hyperSphere) {
			value.setReal(1);
		}
	}
 
Example 18
Source File: PhaseCorrelationTest.java    From BigStitcher with GNU General Public License v2.0 3 votes vote down vote up
@Test
public void testPC() {
	
	// TODO: very large shifts (nearly no overlap) lead to incorrect shift determination (as expected)
	// maybe we can optimize behaviour in this situation
	Img< FloatType > img = ArrayImgs.floats( 200, 200 );
	Random rnd = new Random( seed );
	
	for( FloatType t : img )
		t.set( rnd.nextFloat());
	
	long shiftX = 28;
	long shiftY = 0;
	
	FinalInterval interval1 = new FinalInterval(new long[] {50, 50});
	FinalInterval interval2 = Intervals.translate(interval1, shiftX, 0);
	interval2 = Intervals.translate(interval2, shiftY, 1);

	
	int [] extension = new int[img.numDimensions()];
	Arrays.fill(extension, 10);
	
	RandomAccessibleInterval<FloatType> pcm = PhaseCorrelation2.calculatePCM(Views.interval(img, interval1), Views.zeroMin(Views.interval(img, interval2)), extension, new ArrayImgFactory<FloatType>(), 
			new FloatType(), new ArrayImgFactory<ComplexFloatType>(), new ComplexFloatType(), Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()));
	
	PhaseCorrelationPeak2 shiftPeak = PhaseCorrelation2.getShift(pcm, Views.interval(img, interval1), Views.zeroMin(Views.interval(img, interval2)), 20, 0, false, Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()));
	
	long[] expected = new long[]{shiftX, shiftY};
	long[] found = new long[img.numDimensions()];
	
	
	
	shiftPeak.getShift().localize(found);
	
	assertArrayEquals(expected, found);
	
}
 
Example 19
Source File: BlendedExtendedMirroredRandomAccesible2.java    From BigStitcher with GNU General Public License v2.0 3 votes vote down vote up
public static void main(String[] args) {
	
	new ImageJ();
	Img<FloatType> img1 = ImgLib2Util.openAs32Bit(new File("src/main/resources/img1.tif"));
	long[] dims = new long[img1.numDimensions()];

	BlendedExtendedMirroredRandomAccesible2<FloatType> ext = new BlendedExtendedMirroredRandomAccesible2<FloatType>(img1, new int[]{100, 100, 10});
	
	ext.getExtInterval().dimensions(dims);		
	Img<FloatType> img2 = ArrayImgs.floats(dims);

	// TODO: For efficiency reasons we should now also iterate the BlendedExtendedMirroredRandomAccesible and not the image
	long start = System.currentTimeMillis();
	
	Cursor<FloatType> c = img2.cursor();
	for (FloatType e : Views.iterable(Views.interval(ext, ext.getExtInterval())))
	{
		c.fwd();
		c.get().set(e);
	}
	
	long end = System.currentTimeMillis();		
	System.out.println(end-start);
	
	ImageJFunctions.show(img2);	
	
	//RandomAccessibleInterval<FloatType> img3 = Views.interval(ext, ext.getExtInterval());		
	//ImageJFunctions.show(img3);
	

	

}
 
Example 20
Source File: PhaseCorrelationTest.java    From BigStitcher with GNU General Public License v2.0 2 votes vote down vote up
@Test
public void testPCRealShift() {
	
	// TODO: very large shifts (nearly no overlap) lead to incorrect shift determination (as expected)
	// maybe we can optimize behaviour in this situation
	Img< FloatType > img = ArrayImgs.floats( 200, 200 );
	Random rnd = new Random( seed );
	
	for( FloatType t : img )
		t.set( rnd.nextFloat());
	
	double shiftX = -20.9;
	double shiftY = 1.9;
	
	// to test < 0.5 px off
	final double eps = 0.5;
	
	FinalInterval interval2 = new FinalInterval(new long[] {50, 50});
	
	

	AffineRandomAccessible< FloatType, AffineGet > imgTr = RealViews.affine( Views.interpolate( Views.extendZero( img ), new NLinearInterpolatorFactory<>() ), new Translation2D( shiftX, shiftY ));
	IntervalView< FloatType > img2 = Views.interval( Views.raster( imgTr ), interval2);
	
	int [] extension = new int[img.numDimensions()];
	Arrays.fill(extension, 10);
	
	RandomAccessibleInterval<FloatType> pcm = PhaseCorrelation2.calculatePCM(Views.zeroMin(img2), Views.zeroMin(Views.interval(img, interval2)), extension, new ArrayImgFactory<FloatType>(), 
			new FloatType(), new ArrayImgFactory<ComplexFloatType>(), new ComplexFloatType(), Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()));
	
	PhaseCorrelationPeak2 shiftPeak = PhaseCorrelation2.getShift(pcm, Views.zeroMin(img2), Views.zeroMin(Views.interval(img, interval2)), 20, 0, true, Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()));
	
	
	double[] expected = new double[]{shiftX, shiftY};
	double[] found = new double[img.numDimensions()];
	
	
	
	
	shiftPeak.getSubpixelShift().localize(found);
	
	System.out.println( Util.printCoordinates( found ) );
	
	
	for (int d = 0; d < expected.length; d++)
		assertTrue( Math.abs( expected[d] - found[d] ) < eps );
	
}