Java Code Examples for net.imglib2.realtransform.AffineTransform3D#preConcatenate()

The following examples show how to use net.imglib2.realtransform.AffineTransform3D#preConcatenate() . 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: PaintUtils.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param labelToGlobalTransform
 * @param viewerTransform
 * @param axis
 * 		{@code 0=x, 1=y, 2=z}
 * @param length
 * 		{@code != 0}
 *
 * @return
 */
public static double[] viewerAxisInLabelCoordinates(
		final AffineTransform3D labelToGlobalTransform,
		final AffineTransform3D viewerTransform,
		final int axis,
		final double length)
{
	final AffineTransform3D labelToGlobalTransformWithoutTranslation = duplicateWithoutTranslation(labelToGlobalTransform);
	final AffineTransform3D viewerTransformWithoutTranslation        = duplicateWithoutTranslation(viewerTransform);
	final AffineTransform3D labelToViewerTransformWithoutTranslation = labelToGlobalTransformWithoutTranslation.preConcatenate(viewerTransformWithoutTranslation);

	final double[] viewerUnitAxis = {0.0, 0.0, 0.0};
	viewerUnitAxis[axis] = length;

	labelToViewerTransformWithoutTranslation.applyInverse(viewerUnitAxis, viewerUnitAxis);
	return viewerUnitAxis;
}
 
Example 2
Source File: FlipAxes.java    From BigStitcher with GNU General Public License v2.0 6 votes vote down vote up
public static List<AffineTransform3D> getAccumulativeFlipTransform(final List<AffineTransform3D> currentTransforms, final boolean[] flipAxes)
{
	final List<AffineTransform3D> res = new ArrayList<>();

	for (final AffineTransform3D currentTransform : currentTransforms)
	{
		final Pair< AffineGet, AffineGet > decomp = TransformTools.decomposeIntoAffineAndTranslation( currentTransform );

		final AffineTransform3D flip = new AffineTransform3D();
		for (int d=0; d<3; d++)
		{
			if (flipAxes[d])
				flip.set( -1, d, d );
		}
		// transformation order should be: 
		// move to origin -> inverse affine to axis-aligned pixels -> flip -> re-apply affine -> re-apply translation
		flip.concatenate( decomp.getA().inverse() );
		flip.concatenate( decomp.getB().inverse() );
		flip.preConcatenate( decomp.getA() );
		flip.preConcatenate( decomp.getB() );

		res.add( flip );
	}

	return res;
}
 
Example 3
Source File: SkewImages.java    From BigStitcher with GNU General Public License v2.0 6 votes vote down vote up
public static List<AffineTransform3D> getAccumulativeSkewTransform(final List<AffineTransform3D> currentTransforms, final int skewDirection, final int alongAxis, final double angle)
{
	final List<AffineTransform3D> res = new ArrayList<>();

	for (final AffineTransform3D currentTransform : currentTransforms)
	{
		final Pair< AffineGet, AffineGet > decomp = TransformTools.decomposeIntoAffineAndTranslation( currentTransform );

		final AffineTransform3D skew = new AffineTransform3D();
		skew.set( Math.tan( angle ), skewDirection, alongAxis );
		// transformation order should be: 
		// move to origin -> inverse affine to axis-aligned pixels -> skew -> re-apply affine -> re-apply translation
		skew.concatenate( decomp.getA().inverse() );
		skew.concatenate( decomp.getB().inverse() );
		skew.preConcatenate( decomp.getA() );
		skew.preConcatenate( decomp.getB() );

		res.add( skew );
	}

	return res;
}
 
Example 4
Source File: MultiResolutionRendererGeneric.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
private static <T> RandomAccessible<T> getTransformedSource(
		final Source<T> source,
		final int timepoint,
		final AffineTransform3D viewerTransform,
		final AffineTransform3D screenScaleTransform,
		final int mipmapIndex,
		final CacheHints cacheHints,
		final Interpolation interpolation)
{

	final RandomAccessibleInterval<T> img = source.getSource(timepoint, mipmapIndex);
	if (VolatileCachedCellImg.class.isInstance(img))
		((VolatileCachedCellImg<?, ?>) img).setCacheHints(cacheHints);

	final RealRandomAccessible<T> ipimg = source.getInterpolatedSource(timepoint, mipmapIndex, interpolation);

	final AffineTransform3D sourceToScreen  = viewerTransform.copy();
	final AffineTransform3D sourceTransform = new AffineTransform3D();
	source.getSourceTransform(timepoint, mipmapIndex, sourceTransform);
	sourceToScreen.concatenate(sourceTransform);
	sourceToScreen.preConcatenate(screenScaleTransform);

	LOG.debug(
			"Getting transformed source {} (name={}) for t={} level={} transform={} screen-scale={} hints={} " +
					"interpolation={}",
			source,
			source.getName(),
			timepoint,
			mipmapIndex,
			sourceToScreen,
			screenScaleTransform,
			cacheHints,
			interpolation
	         );

	return RealViews.affine(ipimg, sourceToScreen);
}
 
Example 5
Source File: ViewerState.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
public synchronized int getBestMipMapLevel(final AffineTransform3D screenScaleTransform, final Source<?> source,
                                           final int timepoint)
{
	final AffineTransform3D screenTransform = new AffineTransform3D();
	getViewerTransform(screenTransform);
	screenTransform.preConcatenate(screenScaleTransform);

	return MipmapTransforms.getBestMipMapLevel(screenTransform, source, timepoint);
}
 
Example 6
Source File: ShapeInterpolationMode.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the transformation to bring the mask to the current viewer plane at the requested mipmap level.
 * Ignores the scaling in the viewer and in the mask and instead uses the requested mipmap level for scaling.
 *
 * @param targetLevel
 * @return
 */
private AffineTransform3D getMaskDisplayTransformIgnoreScaling(final int targetLevel)
{
	final AffineTransform3D maskMipmapDisplayTransform = getMaskDisplayTransformIgnoreScaling();
	final int maskLevel = MASK_SCALE_LEVEL;
	if (targetLevel != maskLevel)
	{
		// scale with respect to the given mipmap level
		final int time = activeViewer.getState().getTimepoint();
		final Scale3D relativeScaleTransform = new Scale3D(DataSource.getRelativeScales(source, time, maskLevel, targetLevel));
		maskMipmapDisplayTransform.preConcatenate(relativeScaleTransform.inverse());
	}
	return maskMipmapDisplayTransform;
}
 
Example 7
Source File: TransformConcatenator.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
private void update()
{
	synchronized (lock)
	{
		final AffineTransform3D concatenated = new AffineTransform3D();
		LOG.debug("Concatenating: {} {} {}", displayTransform, globalToViewer, globalTransform); //
		LOG.debug("Concatening with global-to-viewer={} this={}", globalToViewer, this);
		concatenated.set(globalTransform);
		concatenated.preConcatenate(globalToViewer.getTransformCopy());
		concatenated.preConcatenate(displayTransform.getTransformCopy());
		LOG.debug("Concatenated transform: {}", concatenated);
		this.concatenated.setTransform(concatenated);
	}
}
 
Example 8
Source File: PaintUtils.java    From paintera with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This should be equivalent to {@link #maximumVoxelDiagonalLengthPerDimension(AffineTransform3D,
 * AffineTransform3D)}.
 *
 * @param labelToGlobalTransform
 * @param viewerTransform
 *
 * @return
 */
public static double[] labelUnitLengthAlongViewerAxis(
		final AffineTransform3D labelToGlobalTransform,
		final AffineTransform3D viewerTransform)
{
	final AffineTransform3D labelToGlobalTransformWithoutTranslation = duplicateWithoutTranslation(labelToGlobalTransform);
	final AffineTransform3D viewerTransformWithoutTranslation        = duplicateWithoutTranslation(viewerTransform);
	final AffineTransform3D labelToViewerTransformWithoutTranslation = labelToGlobalTransformWithoutTranslation.preConcatenate(viewerTransformWithoutTranslation);

	final double[] unitX = {1.0, 0.0, 0.0};
	final double[] unitY = {0.0, 1.0, 0.0};
	final double[] unitZ = {0.0, 0.0, 1.0};
	labelToViewerTransformWithoutTranslation.applyInverse(unitX, unitX);
	labelToViewerTransformWithoutTranslation.applyInverse(unitY, unitY);
	labelToViewerTransformWithoutTranslation.applyInverse(unitZ, unitZ);

	LinAlgHelpers.normalize(unitX);
	LinAlgHelpers.normalize(unitY);
	LinAlgHelpers.normalize(unitZ);

	labelToViewerTransformWithoutTranslation.apply(unitX, unitX);
	labelToViewerTransformWithoutTranslation.apply(unitY, unitY);
	labelToViewerTransformWithoutTranslation.apply(unitZ, unitZ);

	return new double[] {
			unitX[0],
			unitY[1],
			unitZ[2]
	};

}
 
Example 9
Source File: InterestPointOverlay.java    From SPIM_Registration with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void drawOverlays( final Graphics g )
{
	final Graphics2D graphics = ( Graphics2D ) g;
	final int t = viewer.getState().getCurrentTimepoint();
	final double[] lPos = new double[ 3 ];
	final double[] gPos = new double[ 3 ];
	final AffineTransform3D transform = new AffineTransform3D();

	for ( final InterestPointSource pointSource : interestPointSources )
	{
		pointSource.getLocalToGlobalTransform( t, transform );
		transform.preConcatenate( viewerTransform );

		for ( final RealLocalizable p : pointSource.getLocalCoordinates( t ) )
		{
			p.localize( lPos );
			transform.apply( lPos, gPos );
			final double size = getPointSize( gPos );
			final int x = ( int ) ( gPos[ 0 ] - 0.5 * size );
			final int y = ( int ) ( gPos[ 1 ] - 0.5 * size );
			final int w = ( int ) size;
			graphics.setColor( getColor( gPos ) );
			graphics.fillOval( x, y, w, w );
		}
	}
}
 
Example 10
Source File: GlobalOptimizationSubset.java    From SPIM_Registration with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @param model
 * @param type
 * @param spimData
 * @param channelsToProcess - just to annotate the registration
 * @param description
 * @return
 */
public < M extends Model< M > > boolean computeGlobalOpt(
		final M model,
		final GlobalOptimizationType type,
		final SpimData2 spimData,
		final List< ChannelProcess > channelsToProcess,
		final String description )
{
	final HashMap< ViewId, Tile< M > > tiles = GlobalOpt.compute( model, type, this, type.considerTimePointsAsUnit() );

	if ( tiles == null )
		return false;
	
	String channelList = "[";
	for ( final ChannelProcess c : channelsToProcess )
		channelList += c.getLabel() + " (c=" + c.getChannel().getName() + "), ";
	channelList = channelList.substring( 0, channelList.length() - 2 ) + "]";

	final AffineTransform3D mapBackModel;
	
	// TODO: Map back first tile as good as possible to original location???
	if ( type.getMapBackReferenceTile( this ) != null && type.getMapBackModel() != null )
		mapBackModel = computeMapBackModel( tiles, type, spimData );
	else
		mapBackModel = null;

	// update the view registrations
	for ( final ViewId viewId : this.getViews() )
	{
		final Tile< M > tile = tiles.get( viewId );
		
		// TODO: we assume that M is an Affine3D, which is not necessarily true
		final Affine3D< ? > tilemodel = (Affine3D< ? >)tile.getModel();
		final double[][] m = new double[ 3 ][ 4 ];
		tilemodel.toMatrix( m );
		
		final AffineTransform3D t = new AffineTransform3D();
		t.set( m[0][0], m[0][1], m[0][2], m[0][3],
			   m[1][0], m[1][1], m[1][2], m[1][3],
			   m[2][0], m[2][1], m[2][2], m[2][3] );
		
		if ( mapBackModel != null )
		{
			t.preConcatenate( mapBackModel );
			IOFunctions.println( "ViewId=" + viewId.getViewSetupId() + ": " + t );
		}
		
		Apply_Transformation.preConcatenateTransform( spimData, viewId, t, description + " on " + channelList );
	}

	return true;
}
 
Example 11
Source File: MultiResolutionRendererGeneric.java    From paintera with GNU General Public License v2.0 4 votes vote down vote up
private <U> VolatileProjector createSingleSourceProjector(
		final SourceAndConverter<U> source,
		final int timepoint,
		final AffineTransform3D viewerTransform,
		final int screenScaleIndex,
		final RandomAccessibleInterval<ARGBType> screenImage,
		final RandomAccessibleInterval<ByteType> mask,
		final Interpolation interpolation,
		final boolean preMultiply)
{
	if (useVolatileIfAvailable)
		if (source.asVolatile() != null)
		{
			LOG.debug(
					"Volatile is available for source={} (name={})",
					source.getSpimSource(),
					source.getSpimSource().getName()
			         );
			return createSingleSourceVolatileProjector(
					source.asVolatile(),
					timepoint,
					screenScaleIndex,
					viewerTransform,
					screenImage,
					mask,
					interpolation,
					preMultiply
			                                          );
		}
		else if (source.getSpimSource().getType() instanceof Volatile)
		{
			LOG.debug(
					"Casting to volatile source:{} (name={})",
					source.getSpimSource(),
					source.getSpimSource().getName()
			         );
			@SuppressWarnings("unchecked") final SourceAndConverter<? extends Volatile<?>> vsource =
					(SourceAndConverter<? extends Volatile<?>>) source;
			return createSingleSourceVolatileProjector(
					vsource,
					timepoint,
					screenScaleIndex,
					viewerTransform,
					screenImage,
					mask,
					interpolation,
					preMultiply
			                                          );
		}

	final AffineTransform3D screenScaleTransform = screenScaleTransforms[currentScreenScaleIndex];
	final AffineTransform3D screenTransform      = viewerTransform.copy();
	screenTransform.preConcatenate(screenScaleTransform);
	final int bestLevel = MipmapTransforms.getBestMipMapLevel(screenTransform, source.getSpimSource(), timepoint);
	LOG.debug("Using bestLevel={}", bestLevel);
	return new SimpleVolatileProjector<>(
			getTransformedSource(
					source.getSpimSource(),
					timepoint,
					viewerTransform,
					screenScaleTransform,
					bestLevel,
					null,
					interpolation
				),
			source.getConverter(),
			Views.stack(screenImage),
			numRenderingThreads,
			renderingExecutorService
	);
}
 
Example 12
Source File: TileConfigurationHelpers.java    From BigStitcher with GNU General Public License v2.0 4 votes vote down vote up
public static void updateBDVPreview(Map<ViewId, Translation3D> locations, boolean pixelUnits, boolean keepRotation,
		AbstractSpimData< ? > data, BigDataViewer bdv)
{
	if (data == null || bdv == null )
		return;

	final Map< ViewId, Translation3D > transformsForData = getTransformsForData( locations, pixelUnits, data );
	final Collection< BasicViewDescription< ? > > vds = (Collection< BasicViewDescription< ? > >) data.getSequenceDescription().getViewDescriptions().values();
	final int currentTPId = data.getSequenceDescription().getTimePoints().getTimePointsOrdered()
			.get( bdv.getViewer().getState().getCurrentTimepoint() ).getId();
	for ( BasicViewDescription< ? > vd : vds )
	{
		if (vd.getTimePointId() != currentTPId)
			continue;

		final int sourceIdx = StitchingExplorerPanel.getBDVSourceIndex( vd.getViewSetup(), data );
		final SourceState< ? > s = bdv.getViewer().getState().getSources().get( sourceIdx );

		final ViewRegistration vr = data.getViewRegistrations().getViewRegistration( vd );
		final AffineTransform3D inv = vr.getModel().copy().inverse();
		
		final AffineTransform3D calib = new AffineTransform3D();
		calib.set( vr.getTransformList().get( vr.getTransformList().size() - 1 ).asAffine3D().getRowPackedCopy() );

		AffineTransform3D transform;
		if (transformsForData.containsKey( vd ))
		{
			transform  = inv.copy().preConcatenate( calib ).preConcatenate( transformsForData.get( vd ) );
		}
		else
			continue;

		if (keepRotation)
		{
			AffineTransform3D rotation = new AffineTransform3D();
			Pair< Double, Integer > rotAngleAndAxis = RegularTranformHelpers.getRoatationFromMetadata( vd.getViewSetup().getAttribute( Angle.class ) );
			if (rotAngleAndAxis != null)
			{
				rotation.rotate( rotAngleAndAxis.getB(), rotAngleAndAxis.getA() );
				transform.preConcatenate( rotation.copy() );
			}
		}

		( (TransformedSource< ? >) s.getSpimSource() ).setFixedTransform( transform );
	}

	bdv.getViewer().requestRepaint();
}
 
Example 13
Source File: PreviewRegularGridPanel.java    From BigStitcher with GNU General Public License v2.0 4 votes vote down vote up
private void updateBDV()
{

	BigDataViewer bdv = parent.bdvPopup().getBDV();
	if ( bdv != null )

	{
		
		//FilteredAndGroupedExplorerPanel.resetBDVManualTransformations( bdv );

		RegularTranslationParameters params = new RegularTranslationParameters();
		params.nDimensions = 3;
		params.alternating = alternating;
		params.dimensionOrder = dimensionOrder;
		params.increasing = increasing;
		params.overlaps = overlaps;
		params.nSteps = steps;
		params.keepRotation = rotate;

		Dimensions size = parent.getSpimData().getSequenceDescription().getViewDescriptions()
				.get( selectedVDs.get( 0 ).get( 0 ) ).getViewSetup().getSize();
		List< Translation3D > generateRegularGrid = RegularTranformHelpers.generateRegularGrid( params, size );
		int i = 0;
		for ( List< BasicViewDescription< ? > > lvd : selectedVDs )
		{

			// we did not generate enough transformations
			// -> leave the rest of the views as-is
			if (i>generateRegularGrid.size())
				break;

			for ( BasicViewDescription< ? > vd : lvd )
			{
				
				int sourceIdx = StitchingExplorerPanel.getBDVSourceIndex( vd.getViewSetup(), parent.getSpimData() );
				SourceState< ? > s = parent.bdvPopup().getBDV().getViewer().getState().getSources().get( sourceIdx );
				

				ViewRegistration vr = parent.getSpimData().getViewRegistrations().getViewRegistration( vd );
				AffineTransform3D inv = vr.getModel().copy().inverse();
				AffineTransform3D calib = new AffineTransform3D();
				calib.set( vr.getTransformList().get( vr.getTransformList().size() - 1 ).asAffine3D().getRowPackedCopy() );

				//invAndCalib.preConcatenate( vr.getTransformList().get( 0 ).asAffine3D() );

				AffineTransform3D grid = new AffineTransform3D();
				if (i < generateRegularGrid.size())
					grid.set( generateRegularGrid.get( i ).getRowPackedCopy() );

				AffineTransform3D gridTransform = ( i < generateRegularGrid.size() )
						? inv.preConcatenate( grid.copy() ) : inv.copy();

				gridTransform.preConcatenate( calib );

				if (rotate)
				{
					AffineTransform3D rotation = new AffineTransform3D();
					Pair< Double, Integer > rotAngleAndAxis = RegularTranformHelpers.getRoatationFromMetadata( vd.getViewSetup().getAttribute( Angle.class ) );
					if (rotAngleAndAxis != null)
					{
						rotation.rotate( rotAngleAndAxis.getB(), rotAngleAndAxis.getA() );
						gridTransform.preConcatenate( rotation.copy() );
					}
				}

				( (TransformedSource< ? >) s.getSpimSource() ).setFixedTransform( gridTransform );

			}
			i++;
		}

		
		bdv.getViewer().requestRepaint();

	}

}
 
Example 14
Source File: FractalSpimDataGenerator.java    From BigStitcher with GNU General Public License v2.0 4 votes vote down vote up
public static SpimData2 createVirtualSpimData()
{
	// shift and scale the fractal
	final AffineTransform3D m = new AffineTransform3D();
	double scale = 200;
	m.set( scale, 0.0f, 0.0f, 0.0f, 
		   0.0f, scale, 0.0f, 0.0f,
		   0.0f, 0.0f, scale, 0.0f);
	
	final AffineTransform3D mShift = new AffineTransform3D();
	double shift = 100;
	mShift.set( 1.0f, 0.0f, 0.0f, shift, 
				0.0f, 1.0f, 0.0f, shift,
				0.0f, 0.0f, 1.0f, shift
				);
	final AffineTransform3D mShift2 = new AffineTransform3D();
	double shift2x = 1200;
	double shift2y = 300;
	mShift2.set( 1.0f, 0.0f, 0.0f, shift2x, 
				0.0f, 1.0f, 0.0f, shift2y,
				0.0f, 0.0f, 1.0f, 0.0f
				);
	
	final AffineTransform3D mShift3 = new AffineTransform3D();
	double shift3x = 500;
	double shift3y = 1300;
	mShift3.set( 1.0f, 0.0f, 0.0f, shift3x, 
				0.0f, 1.0f, 0.0f, shift3y,
				0.0f, 0.0f, 1.0f, 0.0f
				);
	
	
	AffineTransform3D m2 = m.copy();
	AffineTransform3D m3 = m.copy();
	m.preConcatenate( mShift );
	m2.preConcatenate( mShift2 );
	m3.preConcatenate( mShift3 );
	
	final int tilesX = 7;
	final int tilesY = 6;
	m.preConcatenate( new Translation3D( -300, 0, 0 ) );

	final float correctOverlap = 0.2f;
	final float wrongOverlap = 0.3f;

	Interval start = new FinalInterval( new long[] {-399,-399,0},  new long[] {0, 0, 0});
	List<Interval> intervals = FractalSpimDataGenerator.generateTileList( 
			start, tilesX, tilesY, correctOverlap );
	
	List<RealLocalizable> falseStarts = FractalSpimDataGenerator.getTileMins(
													FractalSpimDataGenerator.generateTileList( start, tilesX, tilesY, wrongOverlap ));
	
	FractalSpimDataGenerator fsdg = new FractalSpimDataGenerator( 3 );
	fsdg.addFractal( m );
	fsdg.addFractal( m2 );
	fsdg.addFractal( m3 );
	
	return fsdg.generateSpimData( intervals , falseStarts);
}
 
Example 15
Source File: PairwiseStitching.java    From BigStitcher with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args)
	{
		final AffineTransform3D m = new AffineTransform3D();
		double scale = 200;
		m.set( scale, 0.0f, 0.0f, 0.0f, 0.0f, scale, 0.0f, 0.0f, 0.0f, 0.0f, scale, 0.0f );

		final AffineTransform3D mShift = new AffineTransform3D();
		double shift = 100;
		mShift.set( 1.0f, 0.0f, 0.0f, shift, 0.0f, 1.0f, 0.0f, shift, 0.0f, 0.0f, 1.0f, shift );
		final AffineTransform3D mShift2 = new AffineTransform3D();
		double shift2x = 1200;
		double shift2y = 300;
		mShift2.set( 1.0f, 0.0f, 0.0f, shift2x, 0.0f, 1.0f, 0.0f, shift2y, 0.0f, 0.0f, 1.0f, 0.0f );

		final AffineTransform3D mShift3 = new AffineTransform3D();
		double shift3x = 500;
		double shift3y = 1300;
		mShift3.set( 1.0f, 0.0f, 0.0f, shift3x, 0.0f, 1.0f, 0.0f, shift3y, 0.0f, 0.0f, 1.0f, 0.0f );

		AffineTransform3D m2 = m.copy();
		AffineTransform3D m3 = m.copy();
		m.preConcatenate( mShift );
		m2.preConcatenate( mShift2 );
		m3.preConcatenate( mShift3 );

		Interval start = new FinalInterval( new long[] { -399, -399, 0 }, new long[] { 0, 0, 1 } );
		List< Interval > intervals = FractalSpimDataGenerator.generateTileList( start, 7, 6, 0.2f );

		List< Interval > falseStarts = FractalSpimDataGenerator.generateTileList( start, 7, 6, 0.30f );

		FractalSpimDataGenerator fsdg = new FractalSpimDataGenerator( 3 );
		fsdg.addFractal( m );
		fsdg.addFractal( m2 );
		fsdg.addFractal( m3 );

		Map< Integer, RandomAccessibleInterval< LongType > > rais = new HashMap< >();
		Map< Integer, TranslationGet > tr = new HashMap< >();

		List< TranslationGet > tileTranslations = FractalSpimDataGenerator.getTileTranslations( falseStarts );

		FractalImgLoader imgLoader = (FractalImgLoader) fsdg.generateSpimData( intervals ).getSequenceDescription()
				.getImgLoader();
		for ( int i = 0; i < intervals.size(); i++ )
		{
			rais.put( i, imgLoader.getImageAtInterval( intervals.get( i ) ) );
			tr.put( i, tileTranslations.get( i ) );
		}

		List< PairwiseStitchingResult< Integer > > pairwiseShifts = getPairwiseShifts( rais, tr,
				new PairwiseStitchingParameters(),
				Executors.newFixedThreadPool( Runtime.getRuntime().availableProcessors() ) );

		
		Map< Integer, AffineGet > collect = tr.entrySet().stream().collect( Collectors.toMap( e -> 
			e.getKey(), e -> {AffineTransform3D res = new AffineTransform3D(); res.set( e.getValue().getRowPackedCopy() ); return res; } ));
		
		// TODO: replace with new globalOpt code
		
//		Map< Set<Integer>, AffineGet > globalOptimization = GlobalTileOptimization.twoRoundGlobalOptimization( new TranslationModel3D(),
//				rais.keySet().stream().map( ( c ) -> {Set<Integer> s = new HashSet<>(); s.add( c ); return s;}).collect( Collectors.toList() ), 
//				null, 
//				collect,
//				pairwiseShifts, new GlobalOptimizationParameters() );
//
//		System.out.println( globalOptimization );
	}
 
Example 16
Source File: TransformationTools.java    From BigStitcher with GNU General Public License v2.0 4 votes vote down vote up
public static < T extends RealType< T > > Pair<Pair< AffineGet, Double >, RealInterval> computeStitchingLucasKanade(
		final Group<? extends ViewId> viewIdsA,
		final Group<? extends ViewId> viewIdsB,
		final ViewRegistrations vrs,
		final LucasKanadeParameters params,
		final AbstractSequenceDescription< ?,? extends BasicViewDescription<?>, ? > sd,
		final GroupedViewAggregator gva,
		final long[] downsampleFactors,
		final ExecutorService service )
{
	
	// the transformation that maps the downsampled image coordinates back to the original input(!) image space
	final AffineTransform3D dsCorrectionT1 = new AffineTransform3D();
	final AffineTransform3D dsCorrectionT2 = new AffineTransform3D();

	// get Overlap Bounding Box
	final List<List<ViewId>> views = new ArrayList<>();
	views.add( new ArrayList<>(viewIdsA.getViews()) );
	views.add( new ArrayList<>(viewIdsB.getViews()) );
	BoundingBoxMaximalGroupOverlap< ViewId > bbDet = new BoundingBoxMaximalGroupOverlap<ViewId>( views, sd, vrs );
	BoundingBox bbOverlap = bbDet.estimate( "Max Overlap" );

	// this should be caught outside of this method already, but check nonetheless
	if (bbOverlap == null)
		return null;

	// get one image per group
	final RandomAccessibleInterval<T> img1 = gva.aggregate( viewIdsA, sd, downsampleFactors, dsCorrectionT1 );	
	final RandomAccessibleInterval<T> img2 = gva.aggregate( viewIdsB, sd, downsampleFactors, dsCorrectionT2 );

	if (img1 == null || img2 == null)
	{
		IOFunctions.println( "WARNING: Tried to open missing View when computing Stitching for " + viewIdsA + " and " + 
					viewIdsB + ". No link between those could be determined");
		return null;
	}

	// get translations
	// TODO: is the 2d check here meaningful?
	boolean is2d = img1.numDimensions() == 2;
	Pair< AffineGet, TranslationGet > t1 = TransformTools.getInitialTransforms( vrs.getViewRegistration(viewIdsA.iterator().next()), is2d, dsCorrectionT1 );
	Pair< AffineGet, TranslationGet > t2 = TransformTools.getInitialTransforms( vrs.getViewRegistration(viewIdsB.iterator().next()), is2d, dsCorrectionT2 );

	final Pair< AffineTransform, Double > result  = PairwiseStitching.getShiftLucasKanade(  img1, img2, t1.getB(), t2.getB(), params, service );

	if (result == null)
		return null;

	// TODO: is scaling just the translational part okay here?
	for (int i = 0; i< result.getA().numDimensions(); ++i)			
		result.getA().set( result.getA().get(i, result.getA().numDimensions()) * downsampleFactors[i], i, result.getA().numDimensions() ); 

	// TODO (?): Different translational part of downsample Transformations should be considered via TransformTools.getInitialTransforms
	// we probalbly do not have to correct for them ?

	// NB: as we will deal in global coordinates, not pixel coordinates in global optimization,
	// calculate global R' = VT^-1 * R * VT from pixel transformation R 
	ViewRegistration vrOld = vrs.getViewRegistration(viewIdsB.iterator().next());
	AffineTransform3D resTransform = new AffineTransform3D();
	resTransform.set( result.getA().getRowPackedCopy() );
	resTransform.concatenate( vrOld.getModel().inverse() );
	resTransform.preConcatenate( vrOld.getModel() );

	IOFunctions.println("resulting transformation (pixel coordinates): " + Util.printCoordinates(result.getA().getRowPackedCopy()));
	IOFunctions.println("resulting transformation (global coordinates): " + Util.printCoordinates(resTransform.getRowPackedCopy()));

	return new ValuePair<>( new ValuePair<>( resTransform, result.getB() ), bbOverlap );
}
 
Example 17
Source File: TransformationTools.java    From BigStitcher with GNU General Public License v2.0 4 votes vote down vote up
public static < T extends RealType< T > > Pair<Pair< AffineGet, Double >, RealInterval> computeStitching(
		final Group<? extends ViewId> viewIdsA,
		final Group<? extends ViewId> viewIdsB,
		final ViewRegistrations vrs,
		final PairwiseStitchingParameters params,
		final AbstractSequenceDescription< ?,? extends BasicViewDescription<?>, ? > sd,
		final GroupedViewAggregator gva,
		final long[] downsampleFactors,
		final ExecutorService service )
{

	// the transformation that maps the downsampled image coordinates back to the original input(!) image space
	final AffineTransform3D dsCorrectionT1 = new AffineTransform3D();
	final AffineTransform3D dsCorrectionT2 = new AffineTransform3D();

	// get Overlap Bounding Box
	final List<List<ViewId>> views = new ArrayList<>();
	views.add( new ArrayList<>(viewIdsA.getViews()) );
	views.add( new ArrayList<>(viewIdsB.getViews()) );
	BoundingBoxMaximalGroupOverlap< ViewId > bbDet = new BoundingBoxMaximalGroupOverlap<ViewId>( views, sd, vrs );
	BoundingBox bbOverlap = bbDet.estimate( "Max Overlap" );

	// this should be caught outside of this method already, but check nonetheless
	if (bbOverlap == null)
		return null;

	// get one image per group
	final RandomAccessibleInterval<T> img1 = gva.aggregate( viewIdsA, sd, downsampleFactors, dsCorrectionT1 );	
	final RandomAccessibleInterval<T> img2 = gva.aggregate( viewIdsB, sd, downsampleFactors, dsCorrectionT2 );

	if (img1 == null || img2 == null)
	{
		IOFunctions.println( "WARNING: Tried to open missing View when computing Stitching for " + viewIdsA + " and " + 
					viewIdsB + ". No link between those could be determined");
		return null;
	}

	// get translations
	// TODO: is the 2d check here meaningful?
	// everything will probably be 3d at this point, since ImgLoaders return 3d images
	boolean is2d = img1.numDimensions() == 2;
	Pair< AffineGet, TranslationGet > t1 = TransformTools.getInitialTransforms( vrs.getViewRegistration(viewIdsA.iterator().next()), is2d, dsCorrectionT1 );
	Pair< AffineGet, TranslationGet > t2 = TransformTools.getInitialTransforms( vrs.getViewRegistration(viewIdsB.iterator().next()), is2d, dsCorrectionT2 );

	final Pair< Translation, Double > result  = PairwiseStitching.getShift( img1, img2, t1.getB(), t2.getB(), params, service );

	if (result == null)
		return null;
	
	for (int i = 0; i< result.getA().numDimensions(); ++i)			
		result.getA().set( result.getA().get(i, result.getA().numDimensions()) * downsampleFactors[i], i ); 

	// TODO (?): Different translational part of downsample Transformations should be considered via TransformTools.getInitialTransforms
	// we probalbly do not have to correct for them ?

	// NB: as we will deal in global coordinates, not pixel coordinates in global optimization,
	// calculate global R' = VT^-1 * R * VT from pixel transformation R 
	ViewRegistration vrOld = vrs.getViewRegistration(viewIdsB.iterator().next());
	AffineTransform3D resTransform = new AffineTransform3D();
	resTransform.set( result.getA().getRowPackedCopy() );
	resTransform.concatenate( vrOld.getModel().inverse() );
	resTransform.preConcatenate( vrOld.getModel() );

	System.out.println("shift (pixel coordinates): " + Util.printCoordinates(result.getA().getTranslationCopy()));
	System.out.println("shift (global coordinates): " + Util.printCoordinates(resTransform.getRowPackedCopy()));
	System.out.print("cross-corr: " + result.getB());

	return new ValuePair<>( new ValuePair<>( resTransform, result.getB() ), bbOverlap );
}
 
Example 18
Source File: MultiResolutionRendererGeneric.java    From paintera with GNU General Public License v2.0 4 votes vote down vote up
private static <T> void prefetch(
		final Source<T> source,
		final int timepoint,
		final AffineTransform3D viewerTransform,
		final AffineTransform3D screenScaleTransform,
		final int mipmapIndex,
		final CacheHints prefetchCacheHints,
		final Dimensions screenInterval,
		final Interpolation interpolation)
{
	final RandomAccessibleInterval<T> img = source.getSource(timepoint, mipmapIndex);
	if (VolatileCachedCellImg.class.isInstance(img))
	{
		final VolatileCachedCellImg<?, ?> cellImg = (VolatileCachedCellImg<?, ?>) img;

		CacheHints hints = prefetchCacheHints;
		if (hints == null)
		{
			final CacheHints d = cellImg.getDefaultCacheHints();
			hints = new CacheHints(LoadingStrategy.VOLATILE, d.getQueuePriority(), false);
		}
		cellImg.setCacheHints(hints);
		final int[] cellDimensions = new int[3];
		cellImg.getCellGrid().cellDimensions(cellDimensions);
		final long[] dimensions = new long[3];
		cellImg.dimensions(dimensions);
		final RandomAccess<?> cellsRandomAccess = cellImg.getCells().randomAccess();

		final AffineTransform3D sourceToScreen  = viewerTransform.copy();
		final AffineTransform3D sourceTransform = new AffineTransform3D();
		source.getSourceTransform(timepoint, mipmapIndex, sourceTransform);
		sourceToScreen.concatenate(sourceTransform);
		sourceToScreen.preConcatenate(screenScaleTransform);

		Prefetcher.fetchCells(
				sourceToScreen,
				cellDimensions,
				dimensions,
				screenInterval,
				interpolation,
				cellsRandomAccess
		                     );
	}
}