/** * Computes a Gaussian convolution with double precision on an entire {@link Img} * * @param sigma - the sigma for the convolution * @param img - the img {@link Img} * @param outofbounds - the {@link OutOfBoundsFactory} * @return the convolved img having the input type */ @SuppressWarnings({"unchecked", "rawtypes"}) public static <T extends RealType<T>> Img<T> inDouble( final double[] sigma, final Img<T> img, final OutOfBoundsFactory<DoubleType, RandomAccessibleInterval<DoubleType>> outofbounds) { try { if (DoubleType.class.isInstance(img.firstElement())) { return (Img) toDouble(sigma, img, outofbounds); } final Img<T> output = img.factory().create(img, img.firstElement()); final RandomAccessible<DoubleType> rIn = Views.extend( new WriteConvertedRandomAccessibleInterval<T, DoubleType>( img, new RealDoubleSamplerConverter<T>()), outofbounds); final RandomAccessible<DoubleType> rOut = new WriteConvertedRandomAccessible<T, DoubleType>( output, new RealDoubleSamplerConverter<T>()); inDouble( sigma, rIn, img, rOut, new Point(sigma.length), img.factory().imgFactory(new DoubleType())); return output; } catch (final IncompatibleTypeException e) { return null; } }
/** * Computes a Gaussian convolution with double precision on an entire {@link Img} * * @param sigma - the sigma for the convolution * @param img - the img {@link Img} * @param outofbounds - the {@link OutOfBoundsFactory} * @return the convolved img in {@link DoubleType} */ public static <T extends RealType<T>> Img<DoubleType> toDouble( final double[] sigma, final Img<T> img, final OutOfBoundsFactory<DoubleType, RandomAccessibleInterval<DoubleType>> outofbounds) { GaussDouble gauss = null; try { if (DoubleType.class.isInstance(img.firstElement())) { @SuppressWarnings({"rawtypes", "unchecked"}) final Img<DoubleType> img2 = (Img) img; gauss = new GaussDouble(sigma, img2); } else { final RandomAccessibleInterval<DoubleType> rIn = new WriteConvertedIterableRandomAccessibleInterval<T, DoubleType, Img<T>>( img, new RealDoubleSamplerConverter<T>()); gauss = new GaussDouble( sigma, Views.extend(rIn, outofbounds), img, img.factory().imgFactory(new DoubleType())); } } catch (final IncompatibleTypeException e) { return null; } gauss.call(); return (Img<DoubleType>) gauss.getResult(); }
@Override public boolean checkInput() { if (!(source.numDimensions() == 2 || source.numDimensions() == 3)) { errorMessage = BASE_ERROR_MSG + "Only operates on 2D or 3D images."; return false; } return true; }
/** {@inheritDoc} */ @Override public Labeling<L> compute(final RandomAccessibleInterval<T> op, final Labeling<L> r) { initRegionGrowing(op); final LinkedList<ValuePair<int[], L>> q = new LinkedList<ValuePair<int[], L>>(); // image and random access to keep track of the already visited // pixel // positions if (m_allowOverlap) { NativeImgLabeling<L, IntType> tmp = new NativeImgLabeling<L, IntType>( new ArrayImgFactory<IntType>().create(resultDims(op), new IntType())); m_visitedLabRA = tmp.randomAccess(); } else { BitType bt = new BitType(); Img<BitType> tmp = null; try { tmp = new ArrayImgFactory<BitType>().imgFactory(bt).create(op, bt); } catch (IncompatibleTypeException e) { // } m_visitedRA = tmp.randomAccess(); } // access to the resulting labeling RandomAccess<LabelingType<L>> resRA = r.randomAccess(); L label; int[] pos = new int[op.numDimensions()]; do { while ((label = nextSeedPosition(pos)) != null) { // already visited? setVisitedPosition(pos); if (isMarkedAsVisited(label)) { continue; } markAsVisited(label); q.addLast(new ValuePair<int[], L>(pos.clone(), label)); // set new labeling resRA.setPosition(pos); setLabel(resRA, label); if (m_mode == GrowingMode.ASYNCHRONOUS) { growProcess(q, resRA, op); } } if (m_mode == GrowingMode.SYNCHRONOUS) { growProcess(q, resRA, op); } } while (hasMoreSeedingPoints()); return r; }
/** * Computes a Gaussian convolution with the precision of the type provided on an entire {@link * Img} * * @param sigma - the sigma for the convolution * @param img - the img {@link Img} * @param outofbounds - the {@link OutOfBoundsFactory} * @return the convolved img */ public static <T extends NumericType<T>> Img<T> inNumericType( final double[] sigma, final Img<T> img, final OutOfBoundsFactory<T, RandomAccessibleInterval<T>> outofbounds) { final Img<T> output = img.factory().create(img, img.firstElement()); inNumericType( sigma, Views.extend(img, outofbounds), img, output, new Point(sigma.length), img.factory()); return output; }
/** Test the Fourier transformation with a known frequency */ @Test public void oneDimensional() throws IncompatibleTypeException { double[] values = {0, 1, 0, -1, 0}; final Img<DoubleType> img = ArrayImgs.doubles(values, 5); final FourierTransform<DoubleType, ComplexDoubleType> fft = new FourierTransform<DoubleType, ComplexDoubleType>(img, new ComplexDoubleType()); fft.process(); Img<ComplexDoubleType> convolved = fft.getResult(); assertEquals(convolved.numDimensions(), 1); }
@Test public void testSingleDilateFull() { final Shape shape = new DiamondShape(1); @SuppressWarnings("unchecked") final Img<ByteType> out1 = (Img<ByteType>) ops.run(DefaultDilate.class, Img.class, in, shape, true); final Img<ByteType> out2 = Dilation.dilateFull(in, shape, 1); final Cursor<ByteType> c1 = out1.cursor(); final Cursor<ByteType> c2 = out2.cursor(); while (c1.hasNext()) assertEquals(c1.next().get(), c2.next().get()); }
void copyWithSourceIteration(final Img<IntType> srcImg, final Img<IntType> dstImg) { final long[] pos = new long[dimensions.length]; final Cursor<IntType> src = srcImg.localizingCursor(); final RandomAccess<IntType> dst = dstImg.randomAccess(); while (src.hasNext()) { src.fwd(); src.localize(pos); dst.setPosition(pos); dst.get().set(src.get()); } }
void copyWithDestIteration(final Img<IntType> srcImg, final Img<IntType> dstImg) { final long[] pos = new long[dstImg.numDimensions()]; final Cursor<IntType> dst = dstImg.localizingCursor(); final RandomAccess<IntType> src = srcImg.randomAccess(); while (dst.hasNext()) { dst.fwd(); dst.localize(pos); src.setPosition(pos); dst.get().set(src.get()); } }
public Example6a1() throws ImgIOException { // open with ImgOpener as a FloatType Img<FloatType> image = new ImgOpener().openImg("DrosophilaWing.tif", new FloatType()); // perform gaussian convolution with float precision double[] sigma = new double[image.numDimensions()]; for (int d = 0; d < image.numDimensions(); ++d) sigma[d] = 8; // convolve & display ImageJFunctions.show(Gauss.toFloat(sigma, image)); }
@Override public void run() { double[] sigmas = sigmas(); @SuppressWarnings("unchecked") Img<T> target = (Img<T>) dataset.getImgPlus(); Img<T> input = target.copy(); ExtendedRandomAccessibleInterval<T, ?> paddedInput = Views.extendMirrorSingle(input); try { Gauss3.gauss(sigmas, paddedInput, target); } catch (Exception e) { cancel(e.getMessage()); } }
private Img<?> getUsableImage(final Img<ComplexType<?>> img) { if (m_imgBuffer.size() > 0) { return m_imgBuffer.poll(); } else { Img tmpImg = m_imgFactory.create(img, m_resultType); // wrap the result image with an ImgView in case the other image has an offset (i.e. minimum) // -> if not set, an iteration order exception will occur long[] min = new long[img.numDimensions()]; img.min(min); return ImgView.wrap(Views.translate(tmpImg, min), tmpImg.factory()); } }
private Img<DoubleType> makeInputImage() { Img<DoubleType> inputImg = allocateImage(); RandomAccess<DoubleType> accessor = inputImg.randomAccess(); long[] pos = new long[2]; for (int x = 0; x < XSIZE; x++) { for (int y = 0; y < YSIZE; y++) { pos[0] = x; pos[1] = y; accessor.setPosition(pos); accessor.get().setReal(x + y); } } return inputImg; }
int[] getImgAsInts(final Img<IntType> img) { final RandomAccess<IntType> a = img.randomAccess(); final int N = (int) img.size(); final int[] data = new int[N]; final long[] dim = new long[img.numDimensions()]; final long[] pos = new long[img.numDimensions()]; img.dimensions(dim); for (int i = 0; i < N; ++i) { IntervalIndexer.indexToPosition(i, dim, pos); a.setPosition(pos); data[i] = a.get().get(); } return data; }
/** Makes sure input is okay and creates output image */ @Override public boolean checkInput() { final Img inputImage = dataset.getImgPlus(); // TODO - raw type required // here inputDimensions = new long[inputImage.numDimensions()]; inputImage.dimensions(inputDimensions); final long[] outputDimensions = flipper.calcOutputDimensions(inputDimensions); outputImage = inputImage.factory().create(outputDimensions, inputImage.firstElement()); return true; }
private static final <R extends RealType<R>> Img<R> processReal( final Img<R> img, final float[] m, final Mode mode, final OutOfBoundsFactory<R, Img<R>> oobf) throws Exception { final InterpolatorFactory<R, RandomAccessible<R>> inter; switch (mode) { case LINEAR: inter = new NLinearInterpolatorFactory<R>(); break; case NEAREST_NEIGHBOR: inter = new NearestNeighborInterpolatorFactory<R>(); break; default: throw new IllegalArgumentException("Scale: don't know how to scale with mode " + mode); } final ImageTransform<R> transform; final ExtendedRandomAccessibleInterval<R, Img<R>> imgExt = Views.extend(img, oobf); if (2 == img.numDimensions()) { // Transform the single-plane image in 2D AffineModel2D aff = new AffineModel2D(); aff.set(m[0], m[4], m[1], m[5], m[3], m[7]); transform = new ImageTransform<R>(imgExt, aff, (InterpolatorFactory) inter); } else if (3 == img.numDimensions()) { // Transform the image in 3D, or each plane in 2D if (m.length < 12) { throw new IllegalArgumentException( "Affine transform in 3D requires a matrix array of 12 elements."); } AffineModel3D aff = new AffineModel3D(); aff.set(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11]); transform = new ImageTransform<R>(imgExt, aff, (InterpolatorFactory) inter); // Ensure Z dimension is not altered if scaleZ is 1: if (Math.abs(m[10] - 1.0f) < 0.000001 && 0 == m[8] && 0 == m[9]) { long[] d = transform.getNewImageSize(); d[2] = img.dimension(2); // 0-based: '2' is the third dimension transform.setNewImageSize(d); } } else { throw new Exception("Affine transform: only 2D and 3D images are supported."); } if (!transform.checkInput() || !transform.process()) { throw new Exception("Could not affine transform the image: " + transform.getErrorMessage()); } return transform.getResult(); }
/** * Computes a Gaussian convolution in-place (temporary imgs are necessary) with the precision of * the type provided on an entire {@link Img} * * @param sigma - the sigma for the convolution * @param img - the img {@link Img} that will be convolved in place */ public static <T extends NumericType<T>> void inNumericTypeInPlace( final double[] sigma, final Img<T> img, final OutOfBoundsFactory<T, RandomAccessibleInterval<T>> outofbounds) { inNumericType( sigma, Views.extend(img, outofbounds), img, img, new Point(sigma.length), img.factory()); }
@Test public void testListDilateFull() { final List<Shape> shapes = new ArrayList<Shape>(); shapes.add(new DiamondShape(1)); shapes.add(new DiamondShape(1)); shapes.add(new RectangleShape(1, false)); shapes.add(new HorizontalLineShape(2, 1, false)); @SuppressWarnings("unchecked") final IterableInterval<ByteType> out1 = (IterableInterval<ByteType>) ops.run(ListDilate.class, IterableInterval.class, in, shapes, true); final Img<ByteType> out2 = Dilation.dilateFull(in, shapes, 1); final Cursor<ByteType> c1 = out1.cursor(); final Cursor<ByteType> c2 = out2.cursor(); while (c1.hasNext()) assertEquals(c1.next().get(), c2.next().get()); }
public Example1c() { // create the ImgFactory based on cells (cellsize = 5x5x5...x5) that will // instantiate the Img final ImgFactory<FloatType> imgFactory = new CellImgFactory<FloatType>(5); // create an 3d-Img with dimensions 20x30x40 (here cellsize is 5x5x5)Ø final Img<FloatType> img1 = imgFactory.create(new long[] {20, 30, 40}, new FloatType()); // create another image with the same size // note that the input provides the size for the new image as it implements // the Interval interface final Img<FloatType> img2 = imgFactory.create(img1, img1.firstElement()); // display both (but they are empty) ImageJFunctions.show(img1); ImageJFunctions.show(img2); }
protected void updateTitle() { String trailer = ""; if (display instanceof ImageDisplay) { ImageDisplayService srv = getContext().getService(ImageDisplayService.class); if (srv != null) { Dataset ds = srv.getActiveDataset((ImageDisplay) display); if (ds != null) { Img<?> img = ds.getImgPlus().getImg(); if (AbstractCellImg.class.isAssignableFrom(img.getClass())) { trailer = " (V)"; } } } } String name = getDisplay().getName(); if (name == null) name = ""; getWindow().setTitle(name + trailer); }
@Override public void run() { if (!threshSrv.hasThreshold(input)) { cancel("This command requires a thresholded image."); return; } ThresholdOverlay thresh = threshSrv.getThreshold(input); PointSetIterator iter = thresh.getPointsWithin().iterator(); if (!iter.hasNext()) { cancel("No pixels are within the threshold"); return; } Dataset ds = dispSrv.getActiveDataset(input); final int numDims = ds.numDimensions(); final long[] dimensions = new long[numDims]; final long[] min = new long[numDims]; /* * First pass - find minima and maxima so we can use a shrunken image in some cases. */ for (int i = 0; i < numDims; i++) { min[i] = (long) Math.floor(thresh.realMin(i)); dimensions[i] = (long) Math.floor(thresh.realMax(i) - thresh.realMin(i) + 1); } final ArrayImg<BitType, BitArray> arrayMask = new ArrayImgFactory<BitType>().createBitInstance(dimensions, 1); final BitType t = new BitType(arrayMask); arrayMask.setLinkedType(t); final Img<BitType> mask = new ImgTranslationAdapter<BitType, ArrayImg<BitType, BitArray>>(arrayMask, min); final RandomAccess<BitType> raMask = mask.randomAccess(); iter.reset(); while (iter.hasNext()) { long[] pos = iter.next(); raMask.setPosition(pos); raMask.get().set(true); } output = new BinaryMaskOverlay(context, new BinaryMaskRegionOfInterest<BitType, Img<BitType>>(mask)); output.setAlpha(alpha); output.setFillColor(color); for (int i = 0; i < numDims; i++) { output.setAxis(ds.getImgPlus().axis(i), i); } }
/** @see LocalContrastThreshold */ @Test public void testLocalContrastThreshold() { ops.run( LocalContrastThreshold.class, out, in, new RectangleShape(3, false), new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE)); assertEquals(out.firstElement().get(), false); }
@Test public void testInplace() { ops.run(DefaultLoopInplace.class, in, inplaceOp, numIterations); // test final Cursor<ByteType> c = in.cursor(); while (c.hasNext()) { org.junit.Assert.assertEquals(numIterations, c.next().get()); } }
public SubpixelLocalization( final Img<T> laPlacian, final List<DifferenceOfGaussianPeak<T>> peaks) { setNumThreads(); this.laPlacian = laPlacian; this.peaks = peaks; this.allowedToMoveInDim = new boolean[laPlacian.numDimensions()]; // principally one can move in any dimension for (int d = 0; d < allowedToMoveInDim.length; ++d) allowedToMoveInDim[d] = true; this.doubleArrayFactory = new ArrayImgFactory<DoubleType>(); }
/** * Converts an {@link Img} into a matrix * * @param maxtrixImg - the input {@link Img} * @return a {@link Matrix} or null if the {@link Img} is not one or two-dimensional */ public static <S extends RealType<S>> Matrix getMatrix(final Img<S> maxtrixImg) { final int numDimensions = maxtrixImg.numDimensions(); if (numDimensions > 2) return null; final Matrix matrix; if (numDimensions == 1) { matrix = new Matrix((int) maxtrixImg.dimension(0), 1); final Cursor<S> cursor = maxtrixImg.localizingCursor(); while (cursor.hasNext()) { cursor.fwd(); matrix.set(cursor.getIntPosition(0), 0, cursor.get().getRealDouble()); } } else { matrix = new Matrix((int) maxtrixImg.dimension(0), (int) maxtrixImg.dimension(1)); final Cursor<S> cursor = maxtrixImg.localizingCursor(); while (cursor.hasNext()) { cursor.fwd(); matrix.set( cursor.getIntPosition(0), cursor.getIntPosition(1), cursor.get().getRealDouble()); } } return matrix; }
/** @see LocalBernsenThreshold */ @Test public void testLocalBernsenThreshold() { ops.run( LocalBernsenThreshold.class, out, in, new RectangleShape(3, false), new OutOfBoundsMirrorFactory<ByteType, Img<ByteType>>(Boundary.SINGLE), 1.0, Double.MAX_VALUE * 0.5); assertEquals(out.firstElement().get(), true); }
/** With a default {@link OutOfBoundsStrategyValueFactory} with @param outside. */ @SuppressWarnings("unchecked") public AbstractAffine3D( final Img<T> img, final float[] matrix, final Mode mode, final Number outside) throws Exception { this( img, matrix, mode, new OutOfBoundsConstantValueFactory<T, Img<T>>( (T) withValue( img, img.firstElement().createVariable(), outside))); // default value is zero }
private static final <T extends RealType<T>> Img<T> process( final Img<ComplexDoubleType> fftImage, final FourierTransform<T, ComplexDoubleType> fft) throws Exception { final InverseFourierTransform<T, ComplexDoubleType> ifft = new InverseFourierTransform<T, ComplexDoubleType>(fftImage, fft); if (!ifft.checkInput() || !ifft.process()) { throw new Exception( "FFT: failed to process for image " + fftImage.getClass() + " -- " + ifft.getErrorMessage()); } return ifft.getResult(); }
public Img<DoubleType> getImage() { // create the ImgFactory based on cells (cellsize = 5x5x5...x5) that will // instantiate the Img final ImgFactory<DoubleType> imgFactory = new CellImgFactory<DoubleType>(5); // create an 2d-Img with dimensions the of the value_array final Img<DoubleType> img1 = imgFactory.create(new long[] {getValues().length, getValues()[0].length}, new DoubleType()); // System.out.println( "Create image with dimension: " + img1.dimension( 0 ) + " " + // img1.dimension( 1 ) ); RandomAccess<DoubleType> ra = img1.randomAccess(); for (int row = 0; row < getValues().length; row++) { for (int col = 0; col < getValues()[0].length; col++) { ra.setPosition(new int[] {row, col}); // System.out.println( "Current cursor: " + ra.getIntPosition( 0 ) + " " + // ra.getIntPosition( 1 ) ); ra.get().set(getValues()[row][col]); } } return img1; }
/** * Computes a Gaussian convolution in-place (temporary imgs are necessary) with float precision on * an entire {@link Img} * * @param sigma - the sigma for the convolution * @param img - the img {@link Img} that will be convolved in place */ public static <T extends RealType<T>> void inFloatInPlace( final double[] sigma, final Img<T> img, final OutOfBoundsFactory<FloatType, RandomAccessibleInterval<FloatType>> outofbounds) { GaussFloat gauss = null; try { if (FloatType.class.isInstance(img.firstElement())) { @SuppressWarnings({"rawtypes", "unchecked"}) final Img<FloatType> img2 = (Img) img; gauss = new GaussFloat( sigma, Views.extend(img2, outofbounds), img2, img2, new Point(sigma.length), img2.factory().imgFactory(new FloatType())); } else { final RandomAccessibleInterval<FloatType> rIn = new WriteConvertedIterableRandomAccessibleInterval<T, FloatType, Img<T>>( img, new RealFloatSamplerConverter<T>()); gauss = new GaussFloat( sigma, Views.extend(rIn, outofbounds), img, rIn, new Point(sigma.length), img.factory().imgFactory(new FloatType())); } } catch (final IncompatibleTypeException e) { System.out.println(e); return; } gauss.call(); }