mpicbg.models.PointMatch Java Examples

The following examples show how to use mpicbg.models.PointMatch. 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: SimpleMatcher.java    From SPIM_Registration with GNU General Public License v2.0 6 votes vote down vote up
@Override
public ArrayList<ArrayList<PointMatch>> createCandidates( final AbstractPointDescriptor<?, ?> pd1, final AbstractPointDescriptor<?, ?> pd2 )
{
	final ArrayList<PointMatch> matches = new ArrayList<PointMatch>( numNeighbors );		
	
	for ( int i = 0; i < numNeighbors; ++i )
	{
		final PointMatch pointMatch = new PointMatch( pd1.getDescriptorPoint( i ), pd2.getDescriptorPoint( i ) );
		matches.add( pointMatch );
	}		

	final ArrayList<ArrayList<PointMatch>> matchesList = new ArrayList<ArrayList<PointMatch>>();		
	matchesList.add( matches );
	
	return matchesList;
}
 
Example #2
Source File: CanvasFeatureMatcherTest.java    From render with GNU General Public License v2.0 6 votes vote down vote up
private void testRANSACFilterWithMinValue(final List<PointMatch> candidates,
                                          final int minNumInliers,
                                          final int expectedInliersSizeAfterFilter)
        throws NotEnoughDataPointsException {

    final List<PointMatch> inliers = new ArrayList<>();

    final int iterations = 1000;
    final float maxEpsilon = 20f;
    final float minInlierRatio = 0.0f;
    final float maxTrust = 3.0f;

    final AffineModel2D model = new AffineModel2D();

    model.filterRansac(candidates,
                       inliers,
                       iterations,
                       maxEpsilon,
                       minInlierRatio,
                       minNumInliers,
                       maxTrust);

    Assert.assertEquals("invalid number of inliers found with min " + minNumInliers,
                        expectedInliersSizeAfterFilter, inliers.size());
}
 
Example #3
Source File: CanvasFeatureMatcherTest.java    From render with GNU General Public License v2.0 6 votes vote down vote up
private static List<List<PointMatch>> validateConsensusSets(final String context,
                                                            final CanvasMatches canvasMatches,
                                                            final CanvasFeatureMatcher matcher,
                                                            final Integer expectedNumberOfConsensusSets) {

    final List<PointMatch> candidates =
            CanvasFeatureMatchResult.convertMatchesToPointMatchList(canvasMatches.getMatches());

    final List<List<PointMatch>> consensusSets = matcher.filterConsensusMatches(candidates);

    if (expectedNumberOfConsensusSets != null) {
        Assert.assertEquals("filter found invalid number of consensus sets for " + context,
                            expectedNumberOfConsensusSets.intValue(), consensusSets.size());
    }

    return consensusSets;
}
 
Example #4
Source File: Utils.java    From render with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sample the average scaling of a given {@link CoordinateTransform} by transferring a set of point samples using
 * the {@link CoordinateTransform} and then least-squares fitting a {@link SimilarityModel2D} to it.
 *
 * @param width  of the samples set
 * @param height of the samples set
 * @param dx     spacing between samples
 *
 * @return average scale factor
 */
public static double sampleAverageScale(final CoordinateTransform ct,
                                        final int width,
                                        final int height,
                                        final double dx) {
    final ArrayList<PointMatch> samples = new ArrayList<>();
    for (double y = 0; y < height; y += dx) {
        for (double x = 0; x < width; x += dx) {
            final Point p = new Point(new double[]{x, y});
            p.apply(ct);
            samples.add(new PointMatch(p, p));
        }
    }
    final AffineModel2D model = new AffineModel2D();
    try {
        model.fit(samples);
    } catch (final NotEnoughDataPointsException | IllDefinedDataPointsException e) {
        LOG.warn("failed to fit samples, returning scale factor of 1", e);
        return 1;
    }
    final double[] data = new double[6];
    model.toArray(data);
    // return 1;
    return Math.sqrt(Math.max(data[0] * data[0] + data[1] * data[1], data[2] * data[2] + data[3] * data[3]));
}
 
Example #5
Source File: ResidualCalculator.java    From render with GNU General Public License v2.0 6 votes vote down vote up
public static List<PointMatch> convertMatchesToLocal(final List<PointMatch> worldMatchList,
                                               final TileSpec pMatchTileSpec,
                                               final TileSpec qMatchTileSpec) {

    final List<PointMatch> localMatchList = new ArrayList<>(worldMatchList.size());
    Point pPoint;
    Point qPoint;
    for (final PointMatch worldMatch : worldMatchList) {
        try {
            pPoint = getLocalPoint(worldMatch.getP1(), pMatchTileSpec);
            qPoint = getLocalPoint(worldMatch.getP2(), qMatchTileSpec);
            localMatchList.add(new PointMatch(pPoint, qPoint));
        } catch (final NoninvertibleModelException e) {
            LOG.warn("skipping match", e);
        }
    }
    return localMatchList;
}
 
Example #6
Source File: ScriptUtil.java    From render with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Fits sampled points to a model.
 *
 * Stolen from
 *
 * <a href="https://github.com/axtimwalde/fiji-scripts/blob/master/TrakEM2/visualize-ct-difference.bsh#L90-L106">
 *     https://github.com/axtimwalde/fiji-scripts/blob/master/TrakEM2/visualize-ct-difference.bsh#L90-L106
 * </a>.
 *
 * @param  model                model to fit (note: model will be changed by this operation).
 * @param  coordinateTransform  transform to apply to each sampled point.
 * @param  sampleWidth          width of each sample.
 * @param  sampleHeight         height of each sample.
 * @param  samplesPerDimension  number of samples to take in each dimension.
 */
public static void fit(final Model<?> model,
                       final CoordinateTransform coordinateTransform,
                       final double sampleWidth,
                       final double sampleHeight,
                       final int samplesPerDimension)
        throws NotEnoughDataPointsException, IllDefinedDataPointsException {

    final List<PointMatch> matches = new ArrayList<>();

    for (int y = 0; y < samplesPerDimension; ++y) {
        final double sampleY = y * sampleHeight;
        for (int x = 0; x < samplesPerDimension; ++x) {
            final double sampleX = x * sampleWidth;
            final Point p = new Point(new double[]{sampleX, sampleY});
            p.apply(coordinateTransform);
            matches.add(new PointMatch(p, p));
        }
    }

    model.fit(matches);
}
 
Example #7
Source File: CubicBSplineTransform.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
@Override
   public < P extends PointMatch >void fit(final Collection< P > matches)
		throws NotEnoughDataPointsException, IllDefinedDataPointsException
{

	final Stack< java.awt.Point > sourcePoints = new Stack<java.awt.Point>();
	final Stack< java.awt.Point > targetPoints = new Stack<java.awt.Point>();

	for ( final P pm : matches )
	{
		final double[] p1 = pm.getP1().getL();
		final double[] p2 = pm.getP2().getL();

		targetPoints.add( new java.awt.Point( ( int )Math.round( p1[ 0 ] ), ( int )Math.round( p1[ 1 ] ) ) );
		sourcePoints.add( new java.awt.Point( ( int )Math.round( p2[ 0 ] ), ( int )Math.round( p2[ 1 ] ) ) );
	}

	final Transformation transf = bUnwarpJ_.computeTransformationBatch(sourceWidth,
			sourceHeight, width, height, sourcePoints, targetPoints, parameter);
	this.set(transf.getIntervals(), transf.getDirectDeformationCoefficientsX(),
			transf.getDirectDeformationCoefficientsY(), width, height);
}
 
Example #8
Source File: Align.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
final static public boolean findModel(
		final Model< ? > model,
		final List< PointMatch > candidates,
		final Collection< PointMatch > inliers,
		final float maxEpsilon,
		final float minInlierRatio,
		final int minNumInliers,
		final boolean rejectIdentity,
		final float identityTolerance )
{
	return findModel(
			model,
			candidates,
			inliers,
			maxEpsilon,
			minInlierRatio,
			minNumInliers,
			rejectIdentity,
			identityTolerance,
			false );
}
 
Example #9
Source File: BlockMatchPairCallable.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
public BlockMatchResults(final Collection<? extends Point> v1,
                         final Collection<? extends Point> v2,
                         final Collection<PointMatch> pm12,
                         final Collection<PointMatch> pm21,
                         final boolean layer1Fixed,
                         final boolean layer2Fixed,
                         final Triple<Integer, Integer, AbstractModel<?>> pair)
{
    this.v1 = v1;
    this.v2 = v2;
    this.pm12 = pm12;
    this.pm21 = pm21;
    this.layer1Fixed = layer1Fixed;
    this.layer2Fixed = layer2Fixed;
    this.pair = pair;
}
 
Example #10
Source File: TranslationInvariantRigidModel2D.java    From SPIM_Registration with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Closed form weighted least squares solution as described by
 * \citet{SchaeferAl06} and implemented by Johannes Schindelin.
 */
@Override
final public < P extends PointMatch >void fit( final Collection< P > matches )
	throws NotEnoughDataPointsException
{
	if ( matches.size() < MIN_NUM_MATCHES ) throw new NotEnoughDataPointsException( matches.size() + " data points are not enough to estimate a 2d rigid model, at least " + MIN_NUM_MATCHES + " data points required." );

	cos = 0;
	sin = 0;
	for ( final P m : matches )
	{
		final double[] p = m.getP1().getL();
		final double[] q = m.getP2().getW();
		final double w = m.getWeight();

		final double x1 = p[ 0 ];
		final double y1 = p[ 1 ]; // x2
		final double x2 = q[ 0 ]; // y1
		final double y2 = q[ 1 ]; // y2
		sin += w * ( x1 * y2 - y1 * x2 ); //   x1 * y2 - x2 * y1 // assuming p1 is x1,x2 and p2 is y1,y2
		cos += w * ( x1 * x2 + y1 * y2 ); //   x1 * y1 + x2 * y2
	}
	final double norm = Math.sqrt( cos * cos + sin * sin );
	cos /= norm;
	sin /= norm;
}
 
Example #11
Source File: CanvasFeatureMatchResult.java    From render with GNU General Public License v2.0 6 votes vote down vote up
public CanvasFeatureMatchResult(final CanvasFeatureMatcher matcher,
                                final List<List<PointMatch>> consensusSetInliers,
                                final int totalNumberOfCandidates) {

    this.matcher = matcher;
    this.consensusSetInliers = consensusSetInliers;
    int totalNumberOfInliers = 0;
    for (final List<PointMatch> setInliers : consensusSetInliers) {
        totalNumberOfInliers += setInliers.size();
    }
    this.totalNumberOfInliers = totalNumberOfInliers;
    if (totalNumberOfCandidates > 0) {
        this.inlierRatio = totalNumberOfInliers / (double) totalNumberOfCandidates;
    } else {
        this.inlierRatio = 0.0;
    }
}
 
Example #12
Source File: Distortion_Correction.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
void visualizePoints( final List< List< PointMatch > > inliers)
{
	final ColorProcessor ip = new ColorProcessor(nlt.getWidth(), nlt.getHeight());
	ip.setColor(Color.red);

	ip.setLineWidth(5);
	for (int i=0; i < inliers.size(); i++){
		for (int j=0; j < inliers.get(i).size(); j++){
			final double[] tmp1 = inliers.get(i).get(j).getP1().getW();
			final double[] tmp2 = inliers.get(i).get(j).getP2().getL();
			ip.setColor(Color.red);
			ip.drawDot((int) tmp2[0], (int) tmp2[1]);
			ip.setColor(Color.blue);
			ip.drawDot((int) tmp1[0], (int) tmp1[1]);
		}
	}

	final ImagePlus points = new ImagePlus("Corresponding Points after correction", ip);
	points.show();
}
 
Example #13
Source File: RegularizedAffineLayerAlignment.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Return the maximum square distance among any pairwise point
 * distances in the P1 points of a list of point matches.
 * This is a rough estimate of the maximum spatial extent of a point
 * cloud that is used to find the 'widest' cloud.
 *
 * @param matches
 * @return
 */
final static private double squareP1LocalWidth( final List< PointMatch > matches )
{
	double dMax = 0;
	for ( int i = 0; i < matches.size(); ++i )
	{
		final PointMatch m1 = matches.get( i );
		for ( int j = i + 1; j < matches.size(); ++j )
		{
			final PointMatch m2 = matches.get( j );
			final double d = Point.squareLocalDistance( m1.getP1(), m2.getP1() );
			if ( d > dMax )
				dMax = d;
		}
	}
	return dMax;
}
 
Example #14
Source File: SubsetMatcher.java    From SPIM_Registration with GNU General Public License v2.0 6 votes vote down vote up
@Override
public ArrayList<ArrayList<PointMatch>> createCandidates( final AbstractPointDescriptor<?, ?> pd1, final AbstractPointDescriptor<?, ?> pd2 )
{
	final ArrayList<ArrayList<PointMatch>> matchesList = new ArrayList<ArrayList<PointMatch>>();

	for ( int a = 0; a < numCombinations; ++a )
		for ( int b = 0; b < numCombinations; ++b )
		{
			final ArrayList<PointMatch> matches = new ArrayList<PointMatch>( subsetSize );

			for ( int i = 0; i < subsetSize; ++i )
			{
				final PointMatch pointMatch = new PointMatch( pd1.getDescriptorPoint( neighbors[ a ][ i ] ), pd2.getDescriptorPoint( neighbors[ b ][ i ] ) );
				matches.add( pointMatch );
			}

			matchesList.add( matches );

		}

	return matchesList;
}
 
Example #15
Source File: SimplePointMatchIdentification.java    From SPIM_Registration with GNU General Public License v2.0 6 votes vote down vote up
@Override
public ArrayList<PointMatch> assignPointMatches( final List<P> target, final List<P> reference )
{
	final ArrayList<PointMatch> pointMatches = new ArrayList<PointMatch>();

	final KDTree<P> kdTreeTarget = new KDTree<P>( target );
	final NearestNeighborSearch<P> nnSearchTarget = new NearestNeighborSearch<P>( kdTreeTarget );

	for ( final P point : reference )
	{
		final P correspondingPoint = nnSearchTarget.findNearestNeighbor( point );

		if ( correspondingPoint.distanceTo( point ) <= distanceThresold )
			pointMatches.add( new PointMatch ( correspondingPoint, point ) );
	}

	return pointMatches;
}
 
Example #16
Source File: TileSPIM.java    From SPIM_Registration with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Apply the current {@link Model} to all local point coordinates.
 * Update {@link #cost} and {@link #distance}.
 *
 */
final public void updateWithDections()
{
	// call the original method
	update();
	
	if ( matches.size() > 0 )
	{
		for ( final PointMatch match : matches )
		{
			final double dl = match.getDistance();
			((AbstractDetection<?>)match.getP1()).setDistance( (float)dl );
			((AbstractDetection<?>)match.getP2()).setDistance( (float)dl );				
		}
	}

}
 
Example #17
Source File: CanvasFeatureMatcher.java    From render with GNU General Public License v2.0 6 votes vote down vote up
private void postProcessInliers(final List<PointMatch> inliers) {

        // TODO: remove this extra check once RANSAC filter issue is fixed
        if ((inliers.size() > 0) && (inliers.size() < minNumInliers)) {
            LOG.warn("removing {} inliers that mysteriously did not get removed with minNumInliers value of {}",
                     inliers.size(), minNumInliers);
            inliers.clear();
        }

        if ((maxNumInliers != null) && (maxNumInliers > 0) && (inliers.size() > maxNumInliers)) {
            LOG.info("filterMatches: randomly selecting {} of {} inliers", maxNumInliers, inliers.size());
            // randomly select maxNumInliers elements by shuffling and then remove excess elements
            Collections.shuffle(inliers);
            inliers.subList(maxNumInliers, inliers.size()).clear();
        }
    }
 
Example #18
Source File: CanvasFeatureMatcher.java    From render with GNU General Public License v2.0 6 votes vote down vote up
public List<PointMatch> filterMatches(final List<PointMatch> candidates,
                                      final Model model) {

    final List<PointMatch> inliers = new ArrayList<>(candidates.size());

    if (candidates.size() > 0) {
        try {
            model.filterRansac(candidates,
                               inliers,
                               iterations,
                               maxEpsilon,
                               minInlierRatio,
                               minNumInliers,
                               maxTrust);
        } catch (final NotEnoughDataPointsException e) {
            LOG.warn("failed to filter outliers", e);
        }

        postProcessInliers(inliers);

    }

    LOG.info("filterMatches: filtered {} inliers from {} candidates", inliers.size(), candidates.size());

    return inliers;
}
 
Example #19
Source File: MatchIntensities.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
final static protected void identityConnect( final Tile< ? > t1, final Tile< ? > t2, final double weight )
{
	final ArrayList< PointMatch > matches = new ArrayList< PointMatch >();
	matches.add( new PointMatch( new Point( new double[] { 0 } ), new Point( new double[] { 0 } ) ) );
	matches.add( new PointMatch( new Point( new double[] { 1 } ), new Point( new double[] { 1 } ) ) );
	t1.connect( t2, matches );
}
 
Example #20
Source File: StitchingTEM.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
/** dx, dy is the position of t2 relative to the 0,0 of t1. */
static private final void addMatches(final AbstractAffineTile2D<?> t1, final AbstractAffineTile2D<?> t2, final double dx, final double dy) {
	final Point p1 = new Point(new double[]{0, 0});
	final Point p2 = new Point(new double[]{dx, dy});
	t1.addMatch(new PointMatch(p2, p1, 1.0f));
	t2.addMatch(new PointMatch(p1, p2, 1.0f));
	t1.addConnectedTile(t2);
	t2.addConnectedTile(t1);
}
 
Example #21
Source File: ICP.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Detects ambigous (and duplicate) {@link PointMatch}es, i.e. if a {@link Point} corresponds with more than one other {@link Point}
 * @param matches - the {@link List} of {@link PointMatch}es
 * @return - the {@link ArrayList} containing the removed ambigous or duplicate {@link PointMatch}es 
 */
public static ArrayList<PointMatch> removeAmbigousMatches( final List<PointMatch> matches )
{
	final ArrayList<Integer> inconsistentCorrespondences = new ArrayList<Integer>();
	final ArrayList<PointMatch> ambigousMatches = new ArrayList<PointMatch>();
	
	for ( int i = 0; i < matches.size(); i++ )
	{
		final Point pointTarget = matches.get( i ).getP1();
		final Point pointReference = matches.get( i ).getP2();

		final ArrayList<Integer> inconsistent = getOccurences( pointTarget, pointReference, matches );
		
		if ( inconsistent.size() > 0 )
			for ( int index : inconsistent )
				if ( !inconsistentCorrespondences.contains( index ) )						
					inconsistentCorrespondences.add( index );
	}

	if ( inconsistentCorrespondences.size() > 0 )
	{
		Collections.sort( inconsistentCorrespondences );
					
		for ( int i = inconsistentCorrespondences.size() - 1; i >= 0; i-- )
		{
			// save the ambigous match
			final PointMatch pm = matches.get( (int)inconsistentCorrespondences.get(i) );				
			ambigousMatches.add( pm );
			
			// the cast to (int) is essential as otherwise he is looking to remove the Integer object that does not exist in the list 
			matches.remove( (int)inconsistentCorrespondences.get(i) );
		}
	}	
	
	return ambigousMatches;
}
 
Example #22
Source File: SquareDistance.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
@Override
public double getSimilarity( final ArrayList<PointMatch> matches )
{
	final int numDimensions = matches.get( 0 ).getP1().getL().length;
	
	double difference = 0;

	for ( final PointMatch match : matches )
		difference += Point.squareDistance( match.getP1(), match.getP2() );
					
	return difference / (double)numDimensions;		
}
 
Example #23
Source File: NonLinearTransformMode.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
private CoordinateTransform createCT() throws Exception
{
	final Collection< PointMatch > pm = new ArrayList<PointMatch>();
	for ( final Point p : points )
	{
		pm.add( new PointMatch( new Point( p.getL() ), new Point( p.getW() ) ) );
	}
	/*
	 * TODO replace this with the desired parameters of the transformation
	 */
	final MovingLeastSquaresTransform2 mlst = new MovingLeastSquaresTransform2();
	mlst.setAlpha( 1.0f );
	Class< ? extends AbstractAffineModel2D< ? > > c = AffineModel2D.class;
	switch (points.size()) {
		case 1:
			c = TranslationModel2D.class;
			break;
		case 2:
			c = SimilarityModel2D.class;
			break;
		default:
			break;
	}
	mlst.setModel( c );
	mlst.setMatches( pm );

	return mlst;
}
 
Example #24
Source File: ModelPriorMatcher.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
@Override
public double getNormalizationFactor( final ArrayList<PointMatch> matches, final Object fitResult ) 
{
	final TranslationInvariantRigidModel3D matchModel = (TranslationInvariantRigidModel3D)fitResult;
	
	/* get input matrices and quaternion that we can alter */
	final Quat4d quaternion = new Quat4d();
	final Matrix3d templateMatrix = new Matrix3d();
	matchModel.getMatrix3d( templateMatrix );
	
	/* Compute the rotation angle between the two rigid 3d transformations */
	templateMatrix.mul( invertedReferenceMatrix );		
       quaternion.set( templateMatrix );
       
       final double angle = Math.max( 5, Math.toDegrees( Math.acos( quaternion.getW() )  * 2 ) ) - 5;
       
       /* Compute vector difference between the two rotation axes */
       //final Vector3f axis = new Vector3f( quaternion.getX(), quaternion.getY(), quaternion.getZ() );
       //axis.normalize();        
      	//final Point3f templateAxis = new Point3f( axis );
       //final float difference = templateAxis.distance( referenceAxis );

       final double weight = ( 1.0f + 0.03f * angle * angle );
       
       
	return weight; 
       //return Math.pow( 10, difference );	
}
 
Example #25
Source File: ModelPriorSubsetMatcher.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
@Override
public double getNormalizationFactor( final ArrayList<PointMatch> matches, final Object fitResult ) 
{
	final TranslationInvariantRigidModel3D matchModel = (TranslationInvariantRigidModel3D)fitResult;
	
	/* get input matrices and quaternion that we can alter */
	final Quat4d quaternion = new Quat4d();
	final Matrix3d templateMatrix = new Matrix3d();
	matchModel.getMatrix3d( templateMatrix );
	
	/* Compute the rotation angle between the two rigid 3d transformations */
	templateMatrix.mul( invertedReferenceMatrix );		
       quaternion.set( templateMatrix );
       
       final float angle = Math.max( 5, (float)Math.toDegrees( Math.acos( quaternion.getW() )  * 2 ) ) - 5;
       
       /* Compute vector difference between the two rotation axes */
       //final Vector3f axis = new Vector3f( quaternion.getX(), quaternion.getY(), quaternion.getZ() );
       //axis.normalize();        
      	//final Point3f templateAxis = new Point3f( axis );
       //final float difference = templateAxis.distance( referenceAxis );

       final float weight = ( 1.0f + 0.03f * angle * angle );
       
       
	return weight; 
       //return Math.pow( 10, difference );	
}
 
Example #26
Source File: LinearDistance.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
@Override
public double getSimilarity( final ArrayList<PointMatch> matches )
{
	final int numDimensions = matches.get( 0 ).getP1().getL().length;
	
	double difference = 0;
	
	for ( final PointMatch match : matches )
		difference += Point.distance( match.getP1(), match.getP2() );
					
	return difference / (double)numDimensions;		
}
 
Example #27
Source File: PolynomialModel2D.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public < P extends PointMatch >void fit( final Collection< P > pointMatches ) throws NotEnoughDataPointsException, IllDefinedDataPointsException
{
	if ( pointMatches.size() < getMinNumMatches() )
		throw new NotEnoughDataPointsException( pointMatches.size() + " data points are not enough to estimate a 2d polynomial of order " + nlt.getDimension() + ", at least " + getMinNumMatches() + " data points required." );

	affine.fit( pointMatches );

	final double h1[][] = new double[ pointMatches.size() ][ 2 ];
    final double h2[][] = new double[ pointMatches.size() ][ 2 ];

    int i = 0;
	for ( final P match : pointMatches )
    {
    	final double[] tmp1 = match.getP1().getL().clone();
    	affine.applyInPlace( tmp1 );

    	final double[] tmp2 = match.getP2().getW();

    	h1[ i ] = new double[]{ tmp1[ 0 ], tmp1[ 1 ] };
		h2[ i ] = new double[]{ tmp2[ 0 ], tmp2[ 1 ] };

		++i;
    }

	nlt.fit( h1, h2, lambda );
}
 
Example #28
Source File: AbstractAffineTile2D.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Remove all virtual {@link PointMatch matches}.
 *
 * TODO Not yet tested---Do we need these virtual connections?
 */
final public void clearVirtualMatches()
{
	for ( final PointMatch m : virtualMatches )
		matches.remove( m );
	virtualMatches.clear();
}
 
Example #29
Source File: Util.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Save a {@link Collection} of {@link PointMatch PointMatches} two-sided.
 * Creates two serialization files which is desperately required to clean
 * up properly invalid serializations on change of a {@link Patch}.
 * 
 * @param project
 * @param key
 * @param prefix
 * @param id1
 * @param id2
 * @param m
 * @return
 */
final static public boolean serializePointMatches(
		final Project project,
		final Object key,
		final String prefix,
		final long id1,
		final long id2,
		final Collection< PointMatch > m )
{
	final ArrayList< PointMatch > list = new ArrayList< PointMatch >();
	list.addAll( m );
	final ArrayList< PointMatch > tsil = new ArrayList< PointMatch >();
	PointMatch.flip( m, tsil );
	
	final String name = prefix == null ? "pointmatches" : prefix + ".pointmatches";
	
	final Loader loader = project.getLoader();
	return
		loader.serialize(
			new PointMatches( key, list ),
			new StringBuilder( loader.getUNUIdFolder() )
				.append( "pointmatches.ser/" )
				.append( FSLoader.createIdPath( Long.toString( id1 ) + "_" + Long.toString( id2 ), name, ".ser" ) ).toString() ) &&
		loader.serialize(
			new PointMatches( key, tsil ),
			new StringBuilder( loader.getUNUIdFolder() )
				.append( "pointmatches.ser/" )
				.append( FSLoader.createIdPath( Long.toString( id2 ) + "_" + Long.toString( id1 ), name, ".ser" ) ).toString() );
}
 
Example #30
Source File: RansacRegressionReduceFilter.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void filter( final List< PointMatch > candidates, final Collection< PointMatch > inliers )
{
	try
	{
		if (
				model.filterRansac(
						candidates,
						inliers,
						iterations,
						maxEpsilon,
						minInlierRatio,
						minNumInliers,
						maxTrust ) )
		{
			model.fit( inliers );


			final double[] minMax = minMax( inliers );

			inliers.clear();

			final Point p1 = new Point( new double[]{ minMax[ 0 ] } );
			final Point p2 = new Point( new double[]{ minMax[ 1 ] } );
			p1.apply( model );
			p2.apply( model );
			inliers.add( new PointMatch( p1, new Point( p1.getW().clone() ) ) );
			inliers.add( new PointMatch( p2, new Point( p2.getW().clone() ) ) );
		}
		else
				inliers.clear();
	}
	catch ( final Exception e )
	{
		inliers.clear();
	}
}