mpicbg.models.CoordinateTransform Java Examples

The following examples show how to use mpicbg.models.CoordinateTransform. 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: Trakem2SolverClient.java    From render with GNU General Public License v2.0 6 votes vote down vote up
private Tile<InterpolatedAffineModel2D<AffineModel2D, B>> buildTileFromSpec(final TileSpec tileSpec) {

        final CoordinateTransformList<CoordinateTransform> transformList = tileSpec.getTransformList();
        final AffineModel2D lastTransform = (AffineModel2D)
                transformList.get(transformList.getList(null).size() - 1);
        final AffineModel2D lastTransformCopy = lastTransform.copy();

        final double sampleWidth = (tileSpec.getWidth() - 1.0) / (parameters.samplesPerDimension - 1.0);
        final double sampleHeight = (tileSpec.getHeight() - 1.0) / (parameters.samplesPerDimension - 1.0);

        final B regularizer = parameters.regularizerModelType.getInstance();

        try {
            ScriptUtil.fit(regularizer, lastTransformCopy, sampleWidth, sampleHeight, parameters.samplesPerDimension);
        } catch (final Throwable t) {
            throw new IllegalArgumentException(regularizer.getClass() + " model derivation failed for tile '" +
                                               tileSpec.getTileId() + "', cause: " + t.getMessage(),
                                               t);
        }

        return new Tile<>(new InterpolatedAffineModel2D<>(lastTransformCopy,
                                                          regularizer,
                                                          parameters.startLambda)); // note: lambda gets reset during optimization loops
    }
 
Example #2
Source File: UtilsTest.java    From render with GNU General Public License v2.0 6 votes vote down vote up
private double deriveMipmapLevel(final TileSpec tileSpec,
                                 final double scale,
                                 final int width,
                                 final int height) {
    final double x = 0;
    final double y = 0;
    final double meshCellSize = 64.0;

    final RenderParameters renderParameters = new RenderParameters(null, x, y, width, height, scale);
    final double levelZeroScale = renderParameters.getRes(renderParameters.getScale());

    final CoordinateTransformList<CoordinateTransform> coordinateTransformList =
            RenderedCanvasMipmapSource.addRenderScaleAndOffset(tileSpec.getTransformList(),
                                                               levelZeroScale,
                                                               scale,
                                                               x,
                                                               y);

    final double sampleAverageScale =
            Utils.sampleAverageScale(coordinateTransformList, width, height, meshCellSize);

    return Utils.bestMipmapLevel(sampleAverageScale);
}
 
Example #3
Source File: TransformMeshTest.java    From render with GNU General Public License v2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {

    tileSpec = TileSpec.fromJson(TILE_SPEC_JSON);

    ctlMipmap = new CoordinateTransformList<>();
    for (final CoordinateTransform t : tileSpec.getTransformList().getList(null)) {
        ctlMipmap.add(t);
    }

    final int downSampleLevels = 0;

    final Map.Entry<Integer, ImageAndMask> mipmapEntry = tileSpec.getFirstMipmapEntry();
    final ImageAndMask imageAndMask = mipmapEntry.getValue();
    ipMipmap = ImageProcessorCache.getNonCachedImage(imageAndMask.getImageUrl(), downSampleLevels, false, false);

    tp = ipMipmap.createProcessor(ipMipmap.getWidth(), ipMipmap.getHeight());

    final String maskUrl = imageAndMask.getMaskUrl();
    maskSourceProcessor = ImageProcessorCache.getNonCachedImage(maskUrl, downSampleLevels, true, false);
    maskTargetProcessor = new ByteProcessor(tp.getWidth(), tp.getHeight());

}
 
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: ScriptUtil.java    From render with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Applies two transforms to a set of sampled locations and calculates the distance between the results
 * for each location.  The maximum distance between all sample locations is returned.
 *
 * Stolen from
 *
 * <a href="https://github.com/axtimwalde/fiji-scripts/blob/master/TrakEM2/visualize-ct-difference.bsh#L56-L72">
 *     https://github.com/axtimwalde/fiji-scripts/blob/master/TrakEM2/visualize-ct-difference.bsh#L56-L72
 * </a>.
 *
 * @param  coordinateTransform1  first transform to apply to all sampled points.
 * @param  coordinateTransform2  comparison transform to apply to all sampled points.
 * @param  sampleWidth           width of each sample.
 * @param  sampleHeight          height of each sample.
 * @param  samplesPerDimension   number of samples to take in each dimension.
 *
 * @return maximum delta between transformations of all sample locations.
 */
public static double calculateMaxDelta(final CoordinateTransform coordinateTransform1,
                                       final CoordinateTransform coordinateTransform2,
                                       final double sampleWidth,
                                       final double sampleHeight,
                                       final int samplesPerDimension) {

    double maxDelta = 0.0;

    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 double[] l1 = new double[]{sampleX, sampleY};
            final double[] l2 = new double[]{sampleX, sampleY};
            coordinateTransform1.applyInPlace(l1);
            coordinateTransform2.applyInPlace(l2);
            final double dx = l1[0] - l2[0];
            final double dy = l1[1] - l2[1];
            final double d = Math.sqrt((dx * dx) + (dy * dy));
            maxDelta = Math.max(maxDelta, d);
        }
    }

    return maxDelta;
}
 
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: TileSpec.java    From render with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param  x  local x coordinate to transform into world coordinate.
 * @param  y  local y coordinate to transform into world coordinate.
 *
 * @return world coordinates (x, y, z) for the specified local coordinates.
 */
public double[] getWorldCoordinates(final double x, final double y) {
    final double[] worldCoordinates;
    final double[] w = new double[] {x, y};

    if (hasTransforms()) {
        final CoordinateTransformList<CoordinateTransform> ctl = getTransformList();
        ctl.applyInPlace(w);
    }

    if (z == null) {
        worldCoordinates = w;
    } else {
        worldCoordinates = new double[]{w[0], w[1], z};
    }

    return worldCoordinates;
}
 
Example #8
Source File: LeafTransformSpec.java    From render with GNU General Public License v2.0 6 votes vote down vote up
private mpicbg.trakem2.transform.CoordinateTransform newInstance()
        throws IllegalArgumentException {

    final Class clazz = getClazz();
    final Object instance;
    try {
        instance = clazz.newInstance();
    } catch (final Exception e) {
        throw new IllegalArgumentException("failed to create instance of transform class '" + className + "'", e);
    }

    final mpicbg.trakem2.transform.CoordinateTransform coordinateTransform;
    if (instance instanceof mpicbg.trakem2.transform.CoordinateTransform) {
        coordinateTransform = (mpicbg.trakem2.transform.CoordinateTransform) instance;
    } else {
        throw new IllegalArgumentException("transform class '" + className + "' does not implement the '" +
                                           mpicbg.trakem2.transform.CoordinateTransform.class + "' interface");
    }

    return coordinateTransform;
}
 
Example #9
Source File: RenderedCanvasMipmapSource.java    From render with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Modifies the specified full scale transform list for the current render context by
 * adding a transform for bounding box offset, scale, and an area offset (for scaled mipmaps).
 *
 * @param  renderTransformList  list of transforms for full scale (and un-clipped) canvas.
 * @param  levelZeroScale       scale factor for transformed components at mipmap level 0.
 * @param  actualMipmapScale    scale factor for transformed components at desired mipmap level.
 * @param  x                    target image left coordinate.
 * @param  y                    target image top coordinate.
 */
public static CoordinateTransformList<CoordinateTransform> addRenderScaleAndOffset(
        final CoordinateTransformList<CoordinateTransform> renderTransformList,
        final double levelZeroScale,
        final double actualMipmapScale,
        final double x,
        final double y) {

    final AffineModel2D scaleAndOffset = new AffineModel2D();

    // always calculate areaOffset for mipmaps
    final double areaOffset = (1 - (actualMipmapScale / levelZeroScale)) * 0.5;

    scaleAndOffset.set(actualMipmapScale,
                       0,
                       0,
                       actualMipmapScale,
                       -(x * actualMipmapScale + areaOffset),
                       -(y * actualMipmapScale + areaOffset));

    renderTransformList.add(scaleAndOffset);

    return renderTransformList;
}
 
Example #10
Source File: RenderedCanvasMipmapSource.java    From render with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a mesh that incorporates a scale transform based upon the mipmap level
 * along with the transforms for the render context.
 *
 * @param  mipmapLevel          source mipmap level.
 * @param  renderTransformList  list of transforms for the render context.
 * @param  fullScaleWidth       full scale width of the source.
 * @param  meshCellSize         desired size of a mesh cell (triangle) in pixels.
 * @param  mipmapWidth          width of the source mipmap.
 * @param  mipmapHeight         height of the source mipmap.
 *
 * @return mesh for mapping pixels.
 */
public static RenderTransformMesh createRenderMesh(final int mipmapLevel,
                                                   final CoordinateTransformList<CoordinateTransform> renderTransformList,
                                                   final int fullScaleWidth,
                                                   final double meshCellSize,
                                                   final int mipmapWidth,
                                                   final int mipmapHeight) {

    // attach mipmap transformation
    final CoordinateTransformList<CoordinateTransform> mipmapLevelTransformList = new CoordinateTransformList<>();
    mipmapLevelTransformList.add(Utils.createScaleLevelTransform(mipmapLevel));
    mipmapLevelTransformList.add(renderTransformList);

    // create mesh
    final RenderTransformMesh mesh = new RenderTransformMesh(
            mipmapLevelTransformList,
            (int) (fullScaleWidth / meshCellSize + 0.5),
            mipmapWidth,
            mipmapHeight);

    mesh.updateAffines();

    return mesh;
}
 
Example #11
Source File: InterpolatedTransformSpec.java    From render with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected CoordinateTransform buildInstance()
        throws IllegalArgumentException {
    return new InterpolatedCoordinateTransform<>(a.buildInstance(),
                                                 b.buildInstance(),
                                                 lambda);
}
 
Example #12
Source File: RenderTransformMesh.java    From render with GNU General Public License v2.0 5 votes vote down vote up
public RenderTransformMesh(
        final CoordinateTransform t,
		final int numX,
		final double width,
		final double height )
{
	this( t, numX, numY( numX, width, height ), width, height );
}
 
Example #13
Source File: RenderTransformMesh.java    From render with GNU General Public License v2.0 5 votes vote down vote up
final static protected void addPointMatch(final int i, final double[][] pq, final double[] point, final CoordinateTransform t, final double x, final double y) {
    point[0] = x;
    point[1] = y;
    t.applyInPlace(point);

    pq[0][i] = x;
    pq[1][i] = y;
    pq[2][i] = point[0];
    pq[3][i] = point[1];
}
 
Example #14
Source File: ReferenceTransformSpec.java    From render with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected CoordinateTransform buildInstance()
        throws IllegalArgumentException {
    if (resolvedInstance == null) {
        throw new IllegalArgumentException("spec reference to id '" + refId + "' has not been resolved");
    }
    return resolvedInstance.buildInstance();
}
 
Example #15
Source File: TileSpec.java    From render with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get a copy of this {@link TileSpec}'s transforms as a {@link CoordinateTransformList}.
 * If this {@link TileSpec} does not have any transforms, an empty list is returned.
 *
 * The returned list is no longer cached, so it can be used/changed safely without affecting this {@link TileSpec}.
 *
 * @return transform list copy for this tile spec.
 *
 * @throws IllegalArgumentException
 *   if the list cannot be generated.
 */
@JsonIgnore
public CoordinateTransformList<CoordinateTransform> getTransformList()
        throws IllegalArgumentException {

    final CoordinateTransformList<CoordinateTransform> ctl;
    if (transforms == null) {
        ctl = new CoordinateTransformList<>();
    } else {
        ctl = transforms.getNewInstanceAsList();
    }

    return ctl;
}
 
Example #16
Source File: HierarchicalDataService.java    From render with GNU General Public License v2.0 5 votes vote down vote up
private AffineModel2D getRelativeAlignedModel(final HierarchicalStack tierStack,
                                              final TileSpec tileSpecForZ,
                                              final StackId alignedStackId)
        throws IllegalArgumentException {

    final AffineModel2D relativeAlignedModel;

    final TransformSpec lastTransformSpec = tileSpecForZ.getLastTransform();

    if (lastTransformSpec != null) {

        final CoordinateTransform lastTransform = lastTransformSpec.getNewInstance();

        if (lastTransform instanceof AffineModel2D) {
            relativeAlignedModel = HierarchicalStack.getFullScaleRelativeModel((AffineModel2D) lastTransform,
                                                                               tierStack.getScale(),
                                                                               tierStack.getFullScaleBounds());
        } else {
            throw new IllegalArgumentException(
                    "Invalid affine data for z " + tileSpecForZ.getZ() +
                    ".  Last transform for tile '" + tileSpecForZ.getTileId() + "' in " +
                    alignedStackId + " is not a 2D affine.  Tile spec is " + tileSpecForZ.toJson());
        }

    } else {
        throw new IllegalArgumentException(
                "Invalid affine data for z " + tileSpecForZ.getZ() +
                ".  No transforms found for tile '" + tileSpecForZ.getTileId() + "' in " +
                alignedStackId + ".  Tile spec is " + tileSpecForZ.toJson());
    }

    return relativeAlignedModel;
}
 
Example #17
Source File: TileSpec.java    From render with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return a coordinate transform mesh built from this spec's list of transforms.
 *
 * @throws IllegalStateException
 *   if width or height have not been defined for this tile.
 */
public CoordinateTransformMesh getCoordinateTransformMesh(final double meshCellSize)
        throws IllegalStateException {

    if (! hasWidthAndHeightDefined()) {
        throw new IllegalStateException("width and height must be set to create transform mesh");
    }

    final CoordinateTransformList<CoordinateTransform> ctList = getTransformList();
    return new CoordinateTransformMesh(ctList,
                                       getNumberOfTrianglesCoveringWidth(meshCellSize),
                                       width,
                                       height);
}
 
Example #18
Source File: TileSpec.java    From render with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return a transform mesh built from this spec's list of transforms.
 *
 * @throws IllegalStateException
 *   if width or height have not been defined for this tile.
 */
public TransformMesh getTransformMesh(final double meshCellSize)
        throws IllegalStateException {

    if (! hasWidthAndHeightDefined()) {
        throw new IllegalStateException("width and height must be set to create transform mesh");
    }

    final CoordinateTransformList<CoordinateTransform> ctList = getTransformList();
    return new TransformMesh(ctList,
                             getNumberOfTrianglesCoveringWidth(meshCellSize),
                             width,
                             height);
}
 
Example #19
Source File: ResolvedTileSpecCollection.java    From render with GNU General Public License v2.0 5 votes vote down vote up
@JsonIgnore
private AffineModel2D getAffineModelForSpec(final String context,
                                            final TransformSpec transformSpec) {
    final CoordinateTransform transform = transformSpec.buildInstance();
    final AffineModel2D affineModel;
    if (transform instanceof AffineModel2D) {
        affineModel = (AffineModel2D) transform;
    }  else if (transform instanceof Affine2D) {
        affineModel = new AffineModel2D();
        affineModel.set(((Affine2D) transform).createAffine());
    } else {
        throw new IllegalArgumentException(context + " transform must implement " + Affine2D.class.getName());
    }
    return affineModel;
}
 
Example #20
Source File: LeafTransformSpec.java    From render with GNU General Public License v2.0 5 votes vote down vote up
protected CoordinateTransform buildInstance()
        throws IllegalArgumentException {

    final mpicbg.trakem2.transform.CoordinateTransform ct = newInstance();
    if (dataString == null) {
        throw new IllegalArgumentException("no dataString defined for leaf transform spec with id '" +
                                           getId() + "'");
    }
    ct.init(dataString);
    return ct;
}
 
Example #21
Source File: ListTransformSpec.java    From render with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected CoordinateTransform buildInstance()
        throws IllegalArgumentException {
    final CoordinateTransformList<CoordinateTransform> ctList = new CoordinateTransformList<>();
    for (final TransformSpec spec : specList) {
        ctList.add(spec.buildInstance());
    }
    return ctList;
}
 
Example #22
Source File: Render.java    From TrakEM2 with GNU General Public License v3.0 5 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 ct
 * @param width of the samples set
 * @param height of the samples set
 * @param dx spacing between samples
 *
 * @return average scale factor
 */
final static protected  double sampleAverageScale( final CoordinateTransform ct, final int width, final int height, final double dx )
{
	final ArrayList< PointMatch > samples = new ArrayList< PointMatch >();
	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 SimilarityModel2D model = new SimilarityModel2D();
	try
	{
		model.fit( samples );
	}
	catch ( final NotEnoughDataPointsException e )
	{
		e.printStackTrace( System.err );
		return 1;
	}
	final double[] data = new double[ 6 ];
	model.toArray( data );
	return Math.sqrt( data[ 0 ] * data[ 0 ] + data[ 1 ] * data[ 1 ] );
}
 
Example #23
Source File: TransformableCanvas.java    From render with GNU General Public License v2.0 4 votes vote down vote up
public TransformableCanvas(final MipmapSource source,
                           final CoordinateTransformList<CoordinateTransform> transformList) {
    this.source = source;
    this.transformList = transformList;
}
 
Example #24
Source File: HierarchicalRoughStackFunction.java    From render with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Integer call(final Double z)
        throws Exception {

    LogUtilities.setupExecutorLog4j(z.toString());

    final StackId montageStackId = tierZeroStack.getParentTierStackId();

    final RenderDataClient montageDataClient =
            new RenderDataClient(baseDataUrl,
                                 montageStackId.getOwner(),
                                 montageStackId.getProject());

    final Bounds montageLayerBounds = montageDataClient.getLayerBounds(montageStackId.getStack(), z);

    final StackId alignedStackId = tierZeroStack.getAlignedStackId();

    final RenderDataClient alignedDataClient =
            new RenderDataClient(baseDataUrl,
                                 alignedStackId.getOwner(),
                                 alignedStackId.getProject());

    final ResolvedTileSpecCollection tileSpecCollection =
            alignedDataClient.getResolvedTiles(alignedStackId.getStack(), z);

    if (tileSpecCollection.getTileCount() != 1) {
        throw new IllegalArgumentException("layer " + z + " in " + alignedStackId + " has " +
                                           tileSpecCollection.getTileCount() + " tile specs (should only be one)");
    }

    final TileSpec layerTileSpec = tileSpecCollection.getTileSpecs().iterator().next();

    final LeafTransformSpec roughAlignmentTransform;

    final TransformSpec lastTransform = layerTileSpec.getLastTransform();
    final CoordinateTransform transformInstance = lastTransform.getNewInstance();

    if (transformInstance instanceof AffineModel2D) {
        final AffineModel2D scaledAffineModel = (AffineModel2D) transformInstance;
        final AffineModel2D fullScaleRoughModel =
                HierarchicalStack.getFullScaleRelativeModel(scaledAffineModel,
                                                            tierZeroStack.getScale(),
                                                            montageLayerBounds);
        final mpicbg.trakem2.transform.AffineModel2D specModel = new mpicbg.trakem2.transform.AffineModel2D();
        specModel.set(fullScaleRoughModel);

        final String roughTransformId = "z_" + z + "_ROUGH_ALIGN";
        roughAlignmentTransform = new LeafTransformSpec(roughTransformId,
                                                        null,
                                                        specModel.getClass().getName(),
                                                        specModel.toDataString());
    } else {
        throw new IllegalArgumentException("last transform for tileId '" + layerTileSpec.getTileId() +
                                           "' is a " + transformInstance.getClass().getName() + " instance");
    }

    final ResolvedTileSpecCollection tileCollection =
            montageDataClient.getResolvedTiles(montageStackId.getStack(), z);

    // tileCollection.addTransformSpecToCollection(roughAlignmentTransform);
    // tileCollection.addReferenceTransformToAllTiles(roughAlignmentTransform.getId(), false);
    tileCollection.preConcatenateTransformToAllTiles(roughAlignmentTransform);

    final RenderDataClient roughDataClient =
            new RenderDataClient(baseDataUrl,
                                 roughStackId.getOwner(),
                                 roughStackId.getProject());
    roughDataClient.saveResolvedTiles(tileCollection, roughStackId.getStack(), z);

    return tileCollection.getTileCount();
}
 
Example #25
Source File: ThinPlateSplineClientTest.java    From render with GNU General Public License v2.0 4 votes vote down vote up
@Test
    public void testBuildTransformSpec() throws Exception {

        final ThinPlateSplineClient.Parameters parameters = new ThinPlateSplineClient.Parameters();

        final double[] sourceXs = { 0.0, 22.0 };
        final double[] sourceYs = { 0.0, 22.0 };
        final double[] targetXs = { 10.0, 32.0 };
        final double[] targetYs = { 10.0, 32.0 };

        final List<Double> landmarkValues = new ArrayList<>();
        for (int i = 0; i < sourceXs.length; i++) {
            landmarkValues.add(sourceXs[i]);
            landmarkValues.add(sourceYs[i]);
        }

        for (int i = 0; i < targetXs.length; i++) {
            landmarkValues.add(targetXs[i]);
            landmarkValues.add(targetYs[i]);
        }

        parameters.numberOfLandmarks = sourceXs.length;
        parameters.landmarkValues = landmarkValues;

        final ThinPlateSplineClient client = new ThinPlateSplineClient(parameters);
        final LeafTransformSpec transformSpec = client.buildTransformSpec();

        final CoordinateTransform transform = transformSpec.getNewInstance();

        final double testDelta = 0.0001;
        for (int i = 0; i < sourceXs.length; i++) {
            final double[] testResult = transform.apply(new double[] { sourceXs[i], sourceYs[i] });
            Assert.assertEquals("invalid x for landmark " + i, targetXs[i], testResult[0], testDelta);
            Assert.assertEquals("invalid y for landmark " + i, targetYs[i], testResult[1], testDelta);
        }

//        ThinPlateSplineClient.main(
//                new String[] { "--numberOfLandmarks", "1",
//                               "--outputFile", "/tmp/foo.json",
//                               "0.0", "0.0",
//                               "10.0", "10.0"
//                });
    }
 
Example #26
Source File: RenderedCanvasMipmapSource.java    From render with GNU General Public License v2.0 4 votes vote down vote up
@Override
public ChannelMap getChannels(final int mipmapLevel)
        throws IllegalArgumentException {

    final ChannelMap targetChannels = new ChannelMap();

    final double levelScale = (1.0 / Math.pow(2.0, mipmapLevel)) * levelZeroScale;
    final int levelWidth = (int) ((fullScaleWidth * levelScale) + 0.5);
    final int levelHeight = (int) ((fullScaleHeight * levelScale) + 0.5);

    for (final String channelName : channelNames) {
        targetChannels.put(channelName,
                           new ImageProcessorWithMasks(
                                   new FloatProcessor(levelWidth, levelHeight),
                                   null, // mask is added by mapPixels call later (if necessary)
                                   null));
    }

    long totalScaleDerivationTime = 0;

    for (final TransformableCanvas canvas : canvasList) {

        final long scaleDerivationStart = System.currentTimeMillis();

        final CoordinateTransformList<CoordinateTransform> renderTransformList =
                addRenderScaleAndOffset(canvas.getTransformList(), levelZeroScale, levelScale, x, y);

        final MipmapSource source = canvas.getSource();

        final double averageScale = Utils.sampleAverageScale(renderTransformList,
                                                             source.getFullScaleWidth(),
                                                             source.getFullScaleHeight(),
                                                             meshCellSize);

        final int componentMipmapLevel = Utils.bestMipmapLevel(averageScale);

        totalScaleDerivationTime += (System.currentTimeMillis() - scaleDerivationStart);

        mapPixels(source,
                  componentMipmapLevel,
                  renderTransformList,
                  meshCellSize,
                  hasMasks,
                  binaryMask,
                  numberOfMappingThreads,
                  skipInterpolation,
                  targetChannels);
    }

    LOG.debug("getChannels: deriving average scale for {} canvases took {} milliseconds",
              canvasList.size(),
              totalScaleDerivationTime);

    return targetChannels;
}
 
Example #27
Source File: ExtractPSF.java    From SPIM_Registration with GNU General Public License v2.0 4 votes vote down vote up
private static float[][] getMinMaxDim( final int[] dimensions, final CoordinateTransform transform )
{
	final int numDimensions = dimensions.length;
	
	final double[] tmp = new double[ numDimensions ];
	final float[][] minMaxDim = new float[ numDimensions ][ 2 ];
	
	for ( int d = 0; d < numDimensions; ++d )
	{
		minMaxDim[ d ][ 0 ] = Float.MAX_VALUE;
		minMaxDim[ d ][ 1 ] = -Float.MAX_VALUE;
	}
	
	// recursively get all corner points of the image, assuming they will still be the extremum points
	// in the transformed image
	final boolean[][] positions = new boolean[ Util.pow( 2, numDimensions ) ][ numDimensions ];
	Util.setCoordinateRecursive( numDimensions - 1, numDimensions, new int[ numDimensions ], positions );
	
	// get the min and max location for each dimension independently  
	for ( int i = 0; i < positions.length; ++i )
	{
		for ( int d = 0; d < numDimensions; ++d )
		{
			if ( positions[ i ][ d ])
				tmp[ d ] = dimensions[ d ] - 1;
			else
				tmp[ d ] = 0;
		}
		
		transform.applyInPlace( tmp );
		
		for ( int d = 0; d < numDimensions; ++d )
		{				
			if ( tmp[ d ] < minMaxDim[ d ][ 0 ]) 
				minMaxDim[ d ][ 0 ] = (float)tmp[ d ];

			if ( tmp[ d ] > minMaxDim[ d ][ 1 ]) 
				minMaxDim[ d ][ 1 ] = (float)tmp[ d ];
		}				
	}
	
	return minMaxDim;
}
 
Example #28
Source File: TransformUtils.java    From SPIM_Registration with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Return the min and max coordinate of the transformed image in each dimension
 * relative to the dimensions of the image it is based on. This is important
 * for computing bounding boxes.
 *
 * @param dimensions - the dimensions of the image
 * @param transform - the transformation
 *
 * @return - double[ numDimensions ][ 2 ], in the respective dimension d
 * double[ d ][ 0 ] is min, double[ d ][ 1 ] is max
 */
public static double[][] getMinMaxDim( final int[] dimensions, final CoordinateTransform transform )
{
	final int numDimensions = dimensions.length;

	final double[] tmp = new double[ numDimensions ];
	final double[][] minMaxDim = new double[ numDimensions ][ 2 ];

	for ( int d = 0; d < numDimensions; ++d )
	{
		minMaxDim[ d ][ 0 ] = Double.MAX_VALUE;
		minMaxDim[ d ][ 1 ] = -Double.MAX_VALUE;
	}

	// recursively get all corner points of the image, assuming they will still be the extremum points
	// in the transformed image
	final boolean[][] positions = new boolean[ Util.pow( 2, numDimensions ) ][ numDimensions ];
	Util.setCoordinateRecursive( numDimensions - 1, numDimensions, new int[ numDimensions ], positions );

	// get the min and max location for each dimension independently
	for ( int i = 0; i < positions.length; ++i )
	{
		for ( int d = 0; d < numDimensions; ++d )
		{
			if ( positions[ i ][ d ])
				tmp[ d ] = dimensions[ d ];
			else
				tmp[ d ] = 0;
		}

		transform.applyInPlace( tmp );

		for ( int d = 0; d < numDimensions; ++d )
		{
			if ( tmp[ d ] < minMaxDim[ d ][ 0 ])
				minMaxDim[ d ][ 0 ] = tmp[ d ];

			if ( tmp[ d ] > minMaxDim[ d ][ 1 ])
				minMaxDim[ d ][ 1 ] = tmp[ d ];
		}
	}

	return minMaxDim;
}
 
Example #29
Source File: AbstractWarpTransformBuilder.java    From render with GNU General Public License v2.0 4 votes vote down vote up
protected static double[] centerToWorld(final TileSpec tileSpec) {
    final double[] center = new double[] { tileSpec.getWidth() / 2.0, tileSpec.getHeight() / 2.0 };
    final CoordinateTransformList<CoordinateTransform> ctl = tileSpec.getTransformList();
    ctl.applyInPlace(center);
    return center;
}
 
Example #30
Source File: TransformableCanvas.java    From render with GNU General Public License v2.0 4 votes vote down vote up
public CoordinateTransformList<CoordinateTransform> getTransformList() {
    return transformList;
}