
// Script function: Align two images using CrossCorrelate Command by shifting the second image (called “image 1” here).
// Requirement: Open two images

// Unless named starting with GlobalSino, EM, My, Self, the function commands are defined 
//by Gatan DM, please see at link: http://www.globalsino.com/EM/page2597.html


image GlobalSinoImageFrontMost, GlobalSinoImageSecondMost
if ( !GetFrontImage( GlobalSinoImageFrontMost ) )
   Throw( "Please open two images which need to be aligned." )
 
GlobalSinoImageSecondMost := FindNextImage( GlobalSinoImageFrontMost )
 
if ( !ImageIsValid( GlobalSinoImageSecondMost ) )
   Throw( "Please open the seond image which needs to be aligned." )
 
image GlobalSinoImageA, GlobalSinoImageB
GetTwoImages ("Select two images to align (image 1 to be aligned): ", GlobalSinoImageA, GlobalSinoImageB)

number EMImageOneX, EMImageOneY, EMImageTwoX, EMImageTwoY
GetSize( GlobalSinoImageA, EMImageOneX, EMImageOneY )
GetSize( GlobalSinoImageB, EMImageTwoX, EMImageTwoY )

if (!((EMImageOneX==EMImageTwoX)&&(EMImageOneY==EMImageTwoY))) 
   Throw( "Please open two images in the same size!" )

image EMCrossCorrelation := CrossCorrelate( GlobalSinoImageA, GlobalSinoImageB )

number EMCrossCorrelationMaxX, EMCrossCorrelationMaxY, EMCrossCorrelationMax
EMCrossCorrelationMax = max( EMCrossCorrelation, EMCrossCorrelationMaxX, EMCrossCorrelationMaxY )
 
number EMShiftSecondImageX = EMCrossCorrelationMaxX - round( EMImageOneX / 2 )
number EMShiftSecondImageY = EMCrossCorrelationMaxY - round( EMImageOneY / 2 )

GlobalSinoImageB = offset (GlobalSinoImageB, -EMShiftSecondImageX, - EMShiftSecondImageY)

showalert ( "The maximum correlation coefficient is " + EMCrossCorrelationMax + " at " + EMCrossCorrelationMaxX + "/" + EMCrossCorrelationMaxY + "." , 2)

if ( !OKCancelDialog( "The two images are aligned. \n" + "Do you want to show the Cross Correlation image?" ) ) Exit( 0 ) 

ShowImage  (EMCrossCorrelation)
