Java Code Examples for net.imglib2.view.Views#iterable()

The following examples show how to use net.imglib2.view.Views#iterable() . 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: FirstIteration.java    From SPIM_Registration with GNU General Public License v2.0 6 votes vote down vote up
public FirstIteration(
		final ImagePortion portion,
		final RandomAccessibleInterval< FloatType > psi,
		final ArrayList< RandomAccessibleInterval< FloatType > > imgs )
{
	this.portion = portion;
	this.psi = psi;
	this.imgs = imgs;

	this.psiIterable = Views.iterable( psi );
	this.iterableImgs = new ArrayList< IterableInterval< FloatType > >();

	this.realSum = new RealSum();

	compatibleIteration = true;

	for ( final RandomAccessibleInterval< FloatType > img : imgs )
	{
		final IterableInterval< FloatType > imgIterable = Views.iterable( img );

		if ( !psiIterable.iterationOrder().equals( imgIterable.iterationOrder() ) )
			compatibleIteration = false;

		this.iterableImgs.add( imgIterable );
	}
}
 
Example 2
Source File: TestImageAccessor.java    From Colocalisation_Analysis with GNU General Public License v3.0 6 votes vote down vote up
/**
 * This method creates a noise image that has a specified mean.
 * Every pixel has a value uniformly distributed around mean with
 * the maximum spread specified.
 *
 * @return a new noise image
 * @throws MissingPreconditionException if specified means and spreads are not valid
 */
public static <T extends RealType<T> & NativeType<T>> RandomAccessibleInterval<T> produceMeanBasedNoiseImage(T type, int width,
		int height, double mean, double spread, double[] smoothingSigma, long seed) throws MissingPreconditionException {
	if (mean < spread || (mean + spread) > type.getMaxValue()) {
		throw new MissingPreconditionException("Mean must be larger than spread, and mean plus spread must be smaller than max of the type");
	}
	// create the new image
	ImgFactory<T> imgFactory = new ArrayImgFactory<T>();
	RandomAccessibleInterval<T> noiseImage = imgFactory.create( new int[] {width, height}, type); // "Noise image");

	Random r = new Random(seed);
	for (T value : Views.iterable(noiseImage)) {
		value.setReal( mean + ( (r.nextDouble() - 0.5) * spread ) );
	}

	return gaussianSmooth(noiseImage, smoothingSigma);
}
 
Example 3
Source File: CommitCanvasN5.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
private static TLongHashSet generateContainedLabelsSet(
		final RandomAccessibleInterval<Pair<UnsignedLongType, LabelMultisetType>> relevantData)
{
	final TLongHashSet currentDataAsSet = new TLongHashSet();
	for (final Pair<UnsignedLongType, LabelMultisetType> p : Views.iterable(relevantData))
	{
		final UnsignedLongType  pa  = p.getA();
		final LabelMultisetType pb  = p.getB();
		final long              pav = pa.getIntegerLong();
		if (pav == Label.INVALID)
		{
			pb
					.entrySet()
					.stream()
					.map(Entry::getElement)
					.mapToLong(Label::id)
					.forEach(currentDataAsSet::add);
		}
		else
		{
			currentDataAsSet.add(pav);
		}
	}
	return currentDataAsSet;
}
 
Example 4
Source File: ColocalisationTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Gaussian Smooth of the input image using intermediate float format.
 * 
 * @param <T>
 * @param img
 * @param sigma
 * @return
 */
public static <T extends RealType<T> & NativeType<T>>
	Img<T> gaussianSmooth(RandomAccessibleInterval<T> img,
		double[] sigma)
{
	Interval interval = Views.iterable(img);

	ImgFactory<T> outputFactory = new ArrayImgFactory<>(Util.getTypeFromInterval(img));
	final long[] dim = new long[img.numDimensions()];
	img.dimensions(dim);
	Img<T> output = outputFactory.create(dim);

	final long[] pos = new long[img.numDimensions()];
	Arrays.fill(pos, 0);
	Localizable origin = new Point(pos);

	ImgFactory<FloatType> tempFactory = new ArrayImgFactory<>(new FloatType());
	RandomAccessible<T> input = Views.extendMirrorSingle(img);
	Gauss.inFloat(sigma, input, interval, output, origin, tempFactory);

	return output;
}
 
Example 5
Source File: ColocalisationTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * This method creates a noise image that has a specified mean. Every pixel
 * has a value uniformly distributed around mean with the maximum spread
 * specified.
 *
 * @return IllegalArgumentException if specified means and spreads are not
 *         valid
 */
public static <T extends RealType<T> & NativeType<T>>
	Img<T> produceMeanBasedNoiseImage(T type, int width,
		int height, double mean, double spread, double[] smoothingSigma,
		long seed) throws IllegalArgumentException
{
	if (mean < spread || (mean + spread) > type.getMaxValue()) {
		throw new IllegalArgumentException(
			"Mean must be larger than spread, and mean plus spread must be smaller than max of the type");
	}
	// create the new image
	ImgFactory<T> imgFactory = new ArrayImgFactory<>(type);
	Img<T> noiseImage = imgFactory.create(width, height);

	Random r = new Random(seed);
	for (T value : Views.iterable(noiseImage)) {
		value.setReal(mean + ((r.nextDouble() - 0.5) * spread));
	}

	// TODO: call Ops filter.gauss instead
	return gaussianSmooth(noiseImage, smoothingSigma);
}
 
Example 6
Source File: ImageStatistics.java    From Colocalisation_Analysis with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Calculates the mean of an image.
 *
 * @param img The image to calculate the mean of
 * @return The mean of the image passed
 */
final public static <T extends RealType<T>> double getImageMean(
		final RandomAccessibleInterval<T> img )
{
	// Count all values using the RealSum class.
       // It prevents numerical instabilities when adding up millions of pixels
       RealSum realSum = new RealSum();
       long count = 0;

       for ( final T type : Views.iterable(img) )
       {
           realSum.add( type.getRealDouble() );
           ++count;
       }

       return realSum.getSum() / count;
}
 
Example 7
Source File: TestImageAccessor.java    From Colocalisation_Analysis with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Gaussian Smooth of the input image using intermediate float format.
 * @param <T>
 * @param img
 * @param sigma
 * @return
 */
public static <T extends RealType<T> & NativeType<T>> RandomAccessibleInterval<T> gaussianSmooth(
		RandomAccessibleInterval<T> img, double[] sigma) {
	Interval interval = Views.iterable(img);

	ImgFactory<T> outputFactory = new ArrayImgFactory<T>(Util.getTypeFromInterval(img));
	final long[] dim = new long[ img.numDimensions() ];
	img.dimensions(dim);
	RandomAccessibleInterval<T> output = outputFactory.create( dim );

	final long[] pos = new long[ img.numDimensions() ];
	Arrays.fill(pos, 0);
	Localizable origin = new Point(pos);

	ImgFactory<FloatType> tempFactory = new ArrayImgFactory<FloatType>(new FloatType());
	RandomAccessible<T> input = Views.extendMirrorSingle(img);
	Gauss.inFloat(sigma, input, interval, output, origin, tempFactory);

	return output;
}
 
Example 8
Source File: PhaseCorrelation2Util.java    From BigStitcher with GNU General Public License v2.0 5 votes vote down vote up
public static <T extends RealType<T>> double getMean(RandomAccessibleInterval<T> img)
{
	// TODO: if #pixels > ???? else RealSum
	// TODO: integral image?
	double sum = 0.0;
	long n = 0;
	for (T pix: Views.iterable(img)){
		sum += pix.getRealDouble();
		n++;
	}
	return sum/n;
}
 
Example 9
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.
 */
public static RandomAccessibleInterval<BitType> createMask(long[] dim, boolean val) {
	RandomAccessibleInterval<BitType> mask = createMask(dim);
	
	for (BitType t : Views.iterable(mask))
		t.set(val);
	
	return mask;
}
 
Example 10
Source File: VolatileHierarchyProjectorPreMultiply.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
public VolatileHierarchyProjectorPreMultiply(
		final List<? extends RandomAccessible<A>> sources,
		final Converter<? super A, ARGBType> converter,
		final RandomAccessibleInterval<ARGBType> target,
		final RandomAccessibleInterval<ByteType> mask,
		final int numThreads,
		final ExecutorService executorService)
{
	super(Math.max(2, sources.get(0).numDimensions()), converter, target);

	this.sources.addAll(sources);
	numInvalidLevels = sources.size();

	this.mask = mask;

	iterableTarget = Views.iterable(target);

	target.min(min);
	target.max(max);
	sourceInterval = new FinalInterval(min, max);

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

	this.numThreads = numThreads;
	this.executorService = executorService;

	lastFrameRenderNanoTime = -1;
	clearMask();
}
 
Example 11
Source File: PainteraCommandLineArgs.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
private static long findMaxId(final RandomAccessibleInterval<? extends IntegerType<?>> rai) {
	long maxId = org.janelia.saalfeldlab.labels.Label.getINVALID();
	for (final IntegerType<?> t : Views.iterable(rai)) {
		final long id = t.getIntegerLong();
		if (id > maxId)
			maxId = id;
	}
	return maxId;
}
 
Example 12
Source File: PainteraAlerts.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
private static long findMaxId(final RandomAccessibleInterval<? extends IntegerType<?>> rai) {
	long maxId = org.janelia.saalfeldlab.labels.Label.getINVALID();
	for (final IntegerType<?> t : Views.iterable(rai)) {
		final long id = t.getIntegerLong();
		if (id > maxId)
			maxId = id;
	}
	return maxId;
}
 
Example 13
Source File: VolatileHierarchyProjector.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Set all pixels in target to 100% transparent zero, and mask to all
 * Integer.MAX_VALUE.
 */
public void clearMask()
{
	for ( final ByteType val : Views.iterable( mask ) )
		val.set( Byte.MAX_VALUE );
	numInvalidLevels = sources.size();
}
 
Example 14
Source File: VolatileHierarchyProjector.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
public VolatileHierarchyProjector(
		final List< ? extends RandomAccessible< A > > sources,
		final Converter< ? super A, B > converter,
		final RandomAccessibleInterval< B > target,
		final RandomAccessibleInterval< ByteType > mask,
		final int numThreads,
		final ExecutorService executorService )
{
	super( Math.max( 2, sources.get( 0 ).numDimensions() ), converter, target );

	this.sources.addAll( sources );
	numInvalidLevels = sources.size();

	this.mask = mask;

	iterableTarget = Views.iterable( target );

	target.min(min);
	target.max(max);
	sourceInterval = new FinalInterval( min, max );

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

	this.numThreads = numThreads;
	this.executorService = executorService;

	lastFrameRenderNanoTime = -1;
	clearMask();
}
 
Example 15
Source File: VolatileHierarchyProjectorPreMultiply.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Set all pixels in target to 100% transparent zero, and mask to all Integer.MAX_VALUE.
 */
public void clearMask()
{
	for (final ByteType val : Views.iterable(mask))
		val.set(Byte.MAX_VALUE);
	numInvalidLevels = sources.size();
}
 
Example 16
Source File: PairwiseStitching.java    From BigStitcher with GNU General Public License v2.0 4 votes vote down vote up
public static void adjustPCM( final RandomAccessibleInterval< FloatType > img, final float min, final ExecutorService taskExecutor )
{
	final IterableInterval< FloatType > iterable = Views.iterable( img );
	
	// split up into many parts for multithreading
	final Vector< ImagePortion > portions = FusionTools.divideIntoPortions( iterable.size() );

	// set up executor service
	final ArrayList< Callable< Void > > tasks = new ArrayList<>();

	for ( final ImagePortion portion : portions )
	{
		tasks.add( new Callable< Void >() 
				{
					@Override
					public Void call() throws Exception
					{
						final Cursor< FloatType > c = iterable.cursor();
						c.jumpFwd( portion.getStartPosition() );

						for ( long j = 0; j < portion.getLoopSize(); ++j )
						{
							final FloatType t = c.next();
							t.set( (float)Math.sqrt( t.get() - min + 0.01 ) );
						}

						return null;
					}
				});
	}

	try
	{
		// invokeAll() returns when all tasks are complete
		taskExecutor.invokeAll( tasks );
	}
	catch ( final Exception e )
	{
		IOFunctions.println( "Failed to subtract: " + e );
	}
}
 
Example 17
Source File: GroupedViewAggregator.java    From BigStitcher with GNU General Public License v2.0 4 votes vote down vote up
public <T extends RealType<T>> Map<BasicViewDescription<?>, RandomAccessibleInterval<T>> pickBrightest(Map<BasicViewDescription< ? >, RandomAccessibleInterval<T>> input)
{

	final HashMap< BasicViewDescription<?>, RandomAccessibleInterval<T>> res = new HashMap<>();

	// combine by all classes for which we take the same action
	// e.g. pick brightest by channels & illums -> combine by those
	final Set<Class<? extends Entity>> groupingSet = new HashSet<>();
	groupingSet.addAll( entityClasses );
	final List< Group< BasicViewDescription< ? > > > grouped = 
				Group.combineBy( new ArrayList<>(input.keySet()), groupingSet );

	for (Group< BasicViewDescription< ? > > g : grouped)
	{
		final List<BasicViewDescription< ? >> vds = new ArrayList<>();
		final List<RandomAccessibleInterval<T>> rais = new ArrayList<>();
		for (BasicViewDescription< ? > vd : g)
		{
			vds.add( vd );
			rais.add(input.get( vd ));
		}

		// quick check if we have only one present image 
		// -> no need to look at the images in that case
		int nonNullCount = 0;
		int nonNullIndex = -1;
		for (int i = 0; i < rais.size(); i++){
			if (rais.get( i ) != null)
				nonNullCount += 1;
				nonNullIndex = i;
		}
		if (nonNullCount == 1)
		{
			res.put( vds.get( nonNullIndex ), rais.get( nonNullIndex ) );
			continue;
		}

		Double max = -Double.MAX_VALUE;
		int maxIdx = -1;
		for (int i = 0; i < rais.size(); i++){

			// a view is missing, do not take it into account
			if (rais.get( i ) == null)
				continue;

			IterableInterval< T > iterableImg = Views.iterable( rais.get( i ) );
			double mean = AdjustInput.sumImg( iterableImg ) / (double)iterableImg.size();
			if (mean > max)
			{
				max = mean;
				maxIdx = i;
			}
		}

		// at least one view (actually two, since we handle that special case above) is present
		if (maxIdx >= 0)
		{
			res.put( vds.get( maxIdx ), rais.get( maxIdx ) );
		}
	}
	return res;
}
 
Example 18
Source File: AbstractThin.java    From imagej-ops with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void compute(final RandomAccessibleInterval<BitType> input,
	final RandomAccessibleInterval<BitType> output)
{
	// Create a new image as a buffer to store the thinning image in each
	// iteration.
	// This image and output are swapped each iteration since we need to work on
	// the image
	// without changing it.

	final Img<BitType> buffer = ops().create().img(input, new BitType());

	final IterableInterval<BitType> it1 = Views.iterable(buffer);
	final IterableInterval<BitType> it2 = Views.iterable(output);

	// Extend the buffer in order to be able to iterate care-free later.
	final RandomAccessible<BitType> ra1 = Views.extendBorder(buffer);
	final RandomAccessible<BitType> ra2 = Views.extendBorder(output);

	// Used only in first iteration.
	RandomAccessible<BitType> currRa = Views.extendBorder(input);

	// Create cursors.
	final Cursor<BitType> firstCursor = it1.localizingCursor();
	Cursor<BitType> currentCursor = Views.iterable(input).localizingCursor();
	final Cursor<BitType> secondCursor = it2.localizingCursor();

	// Create pointers to the current and next cursor and set them to Buffer and
	// output respectively.
	Cursor<BitType> nextCursor;
	nextCursor = secondCursor;

	// The main loop.
	boolean changes = true;
	int i = 0;
	// Until no more changes, do:
	final long[] coordinates = new long[currentCursor.numDimensions()];
	while (changes) {
		changes = false;
		// This For-Loop makes sure, that iterations only end on full cycles (as
		// defined by the strategies).
		for (int j = 0; j < m_strategy.getIterationsPerCycle(); ++j) {
			// For each pixel in the image.
			while (currentCursor.hasNext()) {
				// Move both cursors
				currentCursor.fwd();
				nextCursor.fwd();
				// Get the position of the current cursor.
				currentCursor.localize(coordinates);

				// Copy the value of the image currently operated upon.
				final boolean curr = currentCursor.get().get();
				nextCursor.get().set(curr);

				// Only foreground pixels may be thinned
				if (curr) {

					// Ask the strategy whether to flip the foreground pixel or not.
					final boolean flip = m_strategy.removePixel(coordinates, currRa, j);

					// If yes - change and keep track of the change.
					if (flip) {
						nextCursor.get().set(false);
						changes = true;
					}
				}
			}
			// One step of the cycle is finished, notify the strategy.
			m_strategy.afterCycle();

			// Reset the cursors to the beginning and assign pointers for the next
			// iteration.
			currentCursor.reset();
			nextCursor.reset();

			// Keep track of the most recent image. Needed for output.
			if (currRa == ra2) {
				currRa = ra1;
				currentCursor = firstCursor;
				nextCursor = secondCursor;
			}
			else {
				currRa = ra2;
				currentCursor = secondCursor;
				nextCursor = firstCursor;
			}

			// Keep track of iterations.
			++i;
		}
	}

	// Depending on the iteration count, the final image is either in ra1 or
	// ra2. Copy it to output.
	if (i % 2 == 0) {
		// Ra1 points to img1, ra2 points to output.
		copy(buffer, output);
	}
}
 
Example 19
Source File: DefaultPValue.java    From imagej-ops with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void compute(final RandomAccessibleInterval<T> image1,
	final RandomAccessibleInterval<U> image2, PValueResult output)
{
	final int[] blockSize = blockSize(image1, psfSize);
	final RandomAccessibleInterval<T> trimmedImage1 = trim(image1, blockSize);
	final RandomAccessibleInterval<U> trimmedImage2 = trim(image2, blockSize);
	final T type1 = Util.getTypeFromInterval(image1);

	final double[] sampleDistribution = new double[nrRandomizations];
	final IterableInterval<T> iterableImage1 = Views.iterable(trimmedImage1);
	final IterableInterval<U> iterableImage2 = Views.iterable(trimmedImage2);
	
	// compute actual coloc value
	final double value = op.calculate(iterableImage1, iterableImage2);
	
	// compute shuffled coloc values in parallel
	int threadCount = Runtime.getRuntime().availableProcessors(); // FIXME: conform to Ops threading strategy...
	Random r = new Random(seed);
	long[] seeds = new long[nrRandomizations];
	for (int s = 0; s < nrRandomizations; s++ ) {
		seeds[s] = r.nextLong();
	}
	ArrayList<Future<?>> future = new ArrayList<>(threadCount);
	for (int t = 0; t < threadCount; t++) {
		int offset = t * nrRandomizations / threadCount;
		int count = (t+1) * nrRandomizations / threadCount - offset;
		future.add(ts.run(() -> {
			final ShuffledView<T> shuffled = new ShuffledView<>(trimmedImage1,
				blockSize, seeds[offset]); // a new one per thread and each needs its own seed
			Img<T> buffer = Util.getSuitableImgFactory(shuffled, type1).create(
				shuffled);
			for (int i = 0; i < count; i++) {
				int index = offset + i;
				if (index >= nrRandomizations) break;
				if (i > 0) shuffled.shuffleBlocks(seeds[index]);
				copy(shuffled, buffer);
				sampleDistribution[index] = op.calculate(buffer, iterableImage2);
			}
		}));
	}

	// wait for threads to finish
	try {
		for (int t = 0; t < threadCount; t++) {
			future.get(t).get();
		}
	}
	catch (final InterruptedException | ExecutionException exc) {
		final Throwable cause = exc.getCause();
		if (cause instanceof RuntimeException) throw (RuntimeException) cause;
		throw new RuntimeException(exc);
	}

	output.setColocValue(value);
	output.setColocValuesArray(sampleDistribution);
	output.setPValue(calculatePvalue(value, sampleDistribution));
}
 
Example 20
Source File: FusionHelper.java    From SPIM_Registration with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Normalizes the image to the range [0...1]
 * 
 * @param img - the image to normalize
 * @param min - min value
 * @param max - max value
 * @return - normalized array
 */
public static boolean normalizeImage( final RandomAccessibleInterval< FloatType > img, final float min, final float max )
{
	final float diff = max - min;

	if ( Float.isNaN( diff ) || Float.isInfinite(diff) || diff == 0 )
	{
		IOFunctions.println( "Cannot normalize image, min=" + min + "  + max=" + max );
		return false;
	}

	final IterableInterval< FloatType > iterable = Views.iterable( img );
	
	// split up into many parts for multithreading
	final Vector< ImagePortion > portions = FusionHelper.divideIntoPortions( iterable.size(), Threads.numThreads() * 2 );

	// set up executor service
	final ExecutorService taskExecutor = Executors.newFixedThreadPool( Threads.numThreads() );
	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 Cursor< FloatType > c = iterable.cursor();
						c.jumpFwd( portion.getStartPosition() );
						
						for ( long j = 0; j < portion.getLoopSize(); ++j )
						{
							final FloatType t = c.next();
							
							final float norm = ( t.get() - min ) / diff;
							t.set( norm );
						}
						
						return "";
					}
				});
	}
	
	try
	{
		// invokeAll() returns when all tasks are complete
		taskExecutor.invokeAll( tasks );
	}
	catch ( final InterruptedException e )
	{
		IOFunctions.println( "Failed to compute min/max: " + e );
		e.printStackTrace();
		return false;
	}

	taskExecutor.shutdown();
	
	return true;
}