Search in sources :

Example 1 with ValuePair

use of net.imglib2.util.ValuePair in project imagej-ops by imagej.

the class DefaultConvexHull3D method computeMinMax.

/**
 * Finds for each dimension the min and max vertex.
 *
 * @return min and max vertices of each dimension
 */
private Pair<Double, Vertex[]> computeMinMax(final Set<Vertex> vertices) {
    Vertex[] minMax = new Vertex[6];
    double maxX, maxY, maxZ;
    double minX, minY, minZ;
    Iterator<Vertex> it = vertices.iterator();
    Vertex initPoint = it.next();
    for (int i = 0; i < minMax.length; i++) {
        minMax[i] = initPoint;
    }
    minX = maxX = initPoint.getX();
    minY = maxY = initPoint.getY();
    minZ = maxZ = initPoint.getZ();
    while (it.hasNext()) {
        Vertex v = it.next();
        if (v.getX() > maxX) {
            maxX = v.getX();
            minMax[3] = v;
        } else if (v.getX() < minX) {
            minX = v.getX();
            minMax[0] = v;
        }
        if (v.getY() > maxY) {
            maxY = v.getY();
            minMax[4] = v;
        } else if (v.getY() < minY) {
            minY = v.getY();
            minMax[2] = v;
        }
        if (v.getZ() > maxZ) {
            maxZ = v.getZ();
            minMax[5] = v;
        } else if (v.getZ() < minZ) {
            minZ = v.getZ();
            minMax[3] = v;
        }
    }
    // This epsilon formula comes from John Lloyd's quickhull
    // implementation http://www.cs.ubc.ca/~lloyd/java/quickhull3d.html
    final double epsilon = 3 * DOUBLE_PREC * (Math.max(Math.abs(maxX), Math.abs(minX)) + Math.max(Math.abs(maxY), Math.abs(minY)) + Math.max(Math.abs(maxZ), Math.abs(minZ)));
    return new ValuePair<>(epsilon, minMax);
}
Also used : Vertex(net.imagej.ops.geom.geom3d.mesh.Vertex) ValuePair(net.imglib2.util.ValuePair)

Example 2 with ValuePair

use of net.imglib2.util.ValuePair in project imagej-ops by imagej.

the class DefaultMinorMajorAxis method calculate.

@Override
public Pair<DoubleType, DoubleType> calculate(final Polygon2D input) {
    List<RealLocalizable> points = new ArrayList<>(GeomUtils.vertices(input));
    // Sort RealLocalizables of P by x-coordinate (in case of a tie,
    // sort by
    // y-coordinate). Sorting is counter clockwise.
    Collections.sort(points, new Comparator<RealLocalizable>() {

        @Override
        public int compare(final RealLocalizable o1, final RealLocalizable o2) {
            final Double o1x = new Double(o1.getDoublePosition(0));
            final Double o2x = new Double(o2.getDoublePosition(0));
            final int result = o2x.compareTo(o1x);
            if (result == 0) {
                return new Double(o2.getDoublePosition(1)).compareTo(new Double(o1.getDoublePosition(1)));
            }
            return result;
        }
    });
    points.add(points.get(0));
    // calculate minor and major axis
    double[] minorMajorAxis = getMinorMajorAxis(input, points);
    return new ValuePair<>(new DoubleType(minorMajorAxis[0]), new DoubleType(minorMajorAxis[1]));
}
Also used : RealLocalizable(net.imglib2.RealLocalizable) DoubleType(net.imglib2.type.numeric.real.DoubleType) ValuePair(net.imglib2.util.ValuePair) ArrayList(java.util.ArrayList)

Example 3 with ValuePair

use of net.imglib2.util.ValuePair in project imagej-ops by imagej.

the class DefaultMaximumFeret method calculate.

@Override
public Pair<RealLocalizable, RealLocalizable> calculate(Polygon2D input) {
    final List<? extends RealLocalizable> points = GeomUtils.vertices(function.calculate(input));
    double distance = Double.NEGATIVE_INFINITY;
    RealLocalizable p0 = points.get(0);
    RealLocalizable p1 = points.get(0);
    for (int i = 0; i < points.size(); i++) {
        for (int j = i + 2; j < points.size(); j++) {
            final RealLocalizable tmpP0 = points.get(i);
            final RealLocalizable tmpP1 = points.get(j);
            final double tmp = Math.sqrt(Math.pow(tmpP0.getDoublePosition(0) - tmpP1.getDoublePosition(0), 2) + Math.pow(tmpP0.getDoublePosition(1) - tmpP1.getDoublePosition(1), 2));
            if (tmp > distance) {
                distance = tmp;
                p0 = tmpP0;
                p1 = tmpP1;
            }
        }
    }
    return new ValuePair<>(p0, p1);
}
Also used : RealLocalizable(net.imglib2.RealLocalizable) ValuePair(net.imglib2.util.ValuePair)

Example 4 with ValuePair

use of net.imglib2.util.ValuePair in project imagej-ops by imagej.

the class BoxCount method calculate.

/**
 * Counts the number of foreground sections in the interval repeatedly with
 * different size sections
 *
 * @param input an n-dimensional binary interval
 * @return A list of (log(foreground count), -log(section size))
 *         {@link ValuePair} objects for curve fitting
 */
@Override
public List<ValuePair<DoubleType, DoubleType>> calculate(final RandomAccessibleInterval<B> input) {
    final List<ValuePair<DoubleType, DoubleType>> points = new ArrayList<>();
    final int dimensions = input.numDimensions();
    final long[] sizes = new long[dimensions];
    final long numTranslations = 1 + gridMoves;
    input.dimensions(sizes);
    for (long sectionSize = maxSize; sectionSize >= minSize; sectionSize /= scaling) {
        final long translationAmount = Math.max(1, sectionSize / numTranslations);
        final Stream<long[]> translations = translationStream(numTranslations, translationAmount, dimensions - 1, new long[dimensions]);
        final LongStream foregroundCounts = countTranslatedGrids(input, translations, sizes, sectionSize);
        final long foreground = foregroundCounts.min().orElse(0);
        final double logSize = -Math.log(sectionSize);
        final double logCount = Math.log(foreground);
        final ValuePair<DoubleType, DoubleType> point = new ValuePair<>(new DoubleType(logSize), new DoubleType(logCount));
        points.add(point);
    }
    return points;
}
Also used : DoubleType(net.imglib2.type.numeric.real.DoubleType) ValuePair(net.imglib2.util.ValuePair) ArrayList(java.util.ArrayList) LongStream(java.util.stream.LongStream)

Example 5 with ValuePair

use of net.imglib2.util.ValuePair in project TrakEM2 by trakem2.

the class MatchIntensities method run.

/**
 * @param layers
 * @param radius
 * @param scale
 * @param numCoefficients
 * @param lambda1
 * @param lambda2
 * @param neighborWeight
 * @param roi
 */
public <M extends Model<M> & Affine1D<M>> void run(final List<Layer> layers, final int radius, final double scale, final int numCoefficients, final double lambda1, final double lambda2, final double neighborWeight, final Rectangle roi) throws InterruptedException, ExecutionException {
    final int firstLayerIndex = layerset.getLayerIndex(layers.get(0).getId());
    final int lastLayerIndex = layerset.getLayerIndex(layers.get(layers.size() - 1).getId());
    // final PointMatchFilter filter = new RansacRegressionFilter();
    final PointMatchFilter filter = new RansacRegressionReduceFilter();
    /* collect patches */
    Utils.log("Collecting patches ... ");
    final ArrayList<Patch> patches = new ArrayList<Patch>();
    for (final Layer layer : layers) patches.addAll((Collection) layer.getDisplayables(Patch.class, roi));
    /* delete existing intensity coefficients */
    Utils.log("Clearing existing intensity maps ... ");
    for (final Patch p : patches) p.clearIntensityMap();
    /* generate coefficient tiles for all patches
		 * TODO consider offering alternative models */
    final HashMap<Patch, ArrayList<Tile<? extends M>>> coefficientsTiles = (HashMap) generateCoefficientsTiles(patches, new InterpolatedAffineModel1D<InterpolatedAffineModel1D<AffineModel1D, TranslationModel1D>, IdentityModel>(new InterpolatedAffineModel1D<AffineModel1D, TranslationModel1D>(new AffineModel1D(), new TranslationModel1D(), lambda1), new IdentityModel(), lambda2), numCoefficients * numCoefficients);
    /* completed patches */
    final HashSet<Patch> completedPatches = new HashSet<Patch>();
    /* collect patch pairs */
    Utils.log("Collecting patch pairs ... ");
    final ArrayList<ValuePair<Patch, Patch>> patchPairs = new ArrayList<ValuePair<Patch, Patch>>();
    for (final Patch p1 : patches) {
        completedPatches.add(p1);
        final Rectangle box1 = p1.getBoundingBox().intersection(roi);
        final ArrayList<Patch> p2s = new ArrayList<Patch>();
        /* across adjacent layers */
        final int layerIndex = layerset.getLayerIndex(p1.getLayer().getId());
        for (int i = Math.max(firstLayerIndex, layerIndex - radius); i <= Math.min(lastLayerIndex, layerIndex + radius); ++i) {
            final Layer layer = layerset.getLayer(i);
            if (layer != null)
                p2s.addAll((Collection) layer.getDisplayables(Patch.class, box1));
        }
        for (final Patch p2 : p2s) {
            /*
				 * if this patch had been processed earlier, all matches are
				 * already in
				 */
            if (completedPatches.contains(p2))
                continue;
            patchPairs.add(new ValuePair<Patch, Patch>(p1, p2));
        }
    }
    final int numThreads = Integer.parseInt(layerset.getProperty("n_mipmap_threads", Integer.toString(Runtime.getRuntime().availableProcessors())));
    Utils.log("Matching intensities using " + numThreads + " threads ... ");
    final ExecutorService exec = Executors.newFixedThreadPool(numThreads);
    final ArrayList<Future<?>> futures = new ArrayList<Future<?>>();
    for (final ValuePair<Patch, Patch> patchPair : patchPairs) {
        futures.add(exec.submit(new Matcher(roi, patchPair, (HashMap) coefficientsTiles, filter, scale, numCoefficients)));
    }
    for (final Future<?> future : futures) future.get();
    /* connect tiles within patches */
    Utils.log("Connecting coefficient tiles in the same patch  ... ");
    for (final Patch p1 : completedPatches) {
        /* get the coefficient tiles */
        final ArrayList<Tile<? extends M>> p1CoefficientsTiles = coefficientsTiles.get(p1);
        for (int y = 1; y < numCoefficients; ++y) {
            final int yr = numCoefficients * y;
            final int yr1 = yr - numCoefficients;
            for (int x = 0; x < numCoefficients; ++x) {
                identityConnect(p1CoefficientsTiles.get(yr1 + x), p1CoefficientsTiles.get(yr + x), neighborWeight);
            }
        }
        for (int y = 0; y < numCoefficients; ++y) {
            final int yr = numCoefficients * y;
            for (int x = 1; x < numCoefficients; ++x) {
                final int yrx = yr + x;
                identityConnect(p1CoefficientsTiles.get(yrx), p1CoefficientsTiles.get(yrx - 1), neighborWeight);
            }
        }
    }
    /* optimize */
    Utils.log("Optimizing ... ");
    final TileConfiguration tc = new TileConfiguration();
    for (final ArrayList<Tile<? extends M>> coefficients : coefficientsTiles.values()) {
        // for ( final Tile< ? > t : coefficients )
        // if ( t.getMatches().size() == 0 )
        // IJ.log( "bang" );
        tc.addTiles(coefficients);
    }
    try {
        tc.optimize(0.01f, iterations, iterations, 0.75f);
    } catch (final NotEnoughDataPointsException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (final IllDefinedDataPointsException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    /* save coefficients */
    final double[] ab = new double[2];
    final FSLoader loader = (FSLoader) layerset.getProject().getLoader();
    final String itsDir = loader.getUNUIdFolder() + "trakem2.its/";
    for (final Entry<Patch, ArrayList<Tile<? extends M>>> entry : coefficientsTiles.entrySet()) {
        final FloatProcessor as = new FloatProcessor(numCoefficients, numCoefficients);
        final FloatProcessor bs = new FloatProcessor(numCoefficients, numCoefficients);
        final Patch p = entry.getKey();
        final double min = p.getMin();
        final double max = p.getMax();
        final ArrayList<Tile<? extends M>> tiles = entry.getValue();
        for (int i = 0; i < numCoefficients * numCoefficients; ++i) {
            final Tile<? extends M> t = tiles.get(i);
            final Affine1D<?> affine = t.getModel();
            affine.toArray(ab);
            /* coefficients mapping into existing [min, max] */
            as.setf(i, (float) ab[0]);
            bs.setf(i, (float) ((max - min) * ab[1] + min - ab[0] * min));
        }
        final ImageStack coefficientsStack = new ImageStack(numCoefficients, numCoefficients);
        coefficientsStack.addSlice(as);
        coefficientsStack.addSlice(bs);
        final String itsPath = itsDir + FSLoader.createIdPath(Long.toString(p.getId()), "it", ".tif");
        new File(itsPath).getParentFile().mkdirs();
        IJ.saveAs(new ImagePlus("", coefficientsStack), "tif", itsPath);
    }
    /* update mipmaps */
    for (final Patch p : patches) p.getProject().getLoader().decacheImagePlus(p.getId());
    final ArrayList<Future<Boolean>> mipmapFutures = new ArrayList<Future<Boolean>>();
    for (final Patch p : patches) mipmapFutures.add(p.updateMipMaps());
    for (final Future<Boolean> f : mipmapFutures) f.get();
    Utils.log("Matching intensities done.");
}
Also used : NotEnoughDataPointsException(mpicbg.models.NotEnoughDataPointsException) HashMap(java.util.HashMap) ValuePair(net.imglib2.util.ValuePair) ArrayList(java.util.ArrayList) Rectangle(java.awt.Rectangle) InterpolatedAffineModel1D(mpicbg.models.InterpolatedAffineModel1D) IdentityModel(mpicbg.models.IdentityModel) TranslationModel1D(mpicbg.models.TranslationModel1D) HashSet(java.util.HashSet) FloatProcessor(ij.process.FloatProcessor) ImageStack(ij.ImageStack) IllDefinedDataPointsException(mpicbg.models.IllDefinedDataPointsException) Tile(mpicbg.models.Tile) Layer(ini.trakem2.display.Layer) ImagePlus(ij.ImagePlus) Point(mpicbg.models.Point) FSLoader(ini.trakem2.persistence.FSLoader) ExecutorService(java.util.concurrent.ExecutorService) Collection(java.util.Collection) InterpolatedAffineModel1D(mpicbg.models.InterpolatedAffineModel1D) AffineModel1D(mpicbg.models.AffineModel1D) Future(java.util.concurrent.Future) TileConfiguration(mpicbg.models.TileConfiguration) Patch(ini.trakem2.display.Patch) File(java.io.File)

Aggregations

ValuePair (net.imglib2.util.ValuePair)7 ArrayList (java.util.ArrayList)3 RealLocalizable (net.imglib2.RealLocalizable)3 DoubleType (net.imglib2.type.numeric.real.DoubleType)2 ImagePlus (ij.ImagePlus)1 ImageStack (ij.ImageStack)1 FloatProcessor (ij.process.FloatProcessor)1 Layer (ini.trakem2.display.Layer)1 Patch (ini.trakem2.display.Patch)1 FSLoader (ini.trakem2.persistence.FSLoader)1 Rectangle (java.awt.Rectangle)1 File (java.io.File)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 ExecutorService (java.util.concurrent.ExecutorService)1 Future (java.util.concurrent.Future)1 LongStream (java.util.stream.LongStream)1 AffineModel1D (mpicbg.models.AffineModel1D)1 IdentityModel (mpicbg.models.IdentityModel)1