Gatan | AMETEKSkip to Main Content
No options found

Bin 2D image

DigitalMicrograph Script

Bin pixels in 2D images (demonstrate Slice2 command).

Preview

/////////////////////////////////////////////////////////////////////
// (c) Gatan Inc.
/////////////////////////////////////////////////////////////////////
// This script performs data binning of a 2D image using the slice2 command.
// Pixel intensities of a [bin x bin] area are summed into a single pixel.
//////////////////////////////////////////////////////////////////////
//	last modified 08-August-2014 BS

image img
if ( !GetFrontImage( img ) ) exit(0)				// Exit script if no front-image found
if ( 2 != ImageGetNumDimensions( img ) ) exit(0)	// Exit script if the image is not 2D

// Ask user to provide a interger number for binning.
// Refuse entries which are no integers or <=0
// Exit script if user clicks the cancel button
number bin=0
while( (0>=bin) || ( 0 != mod(bin,1) ) )
{
	if ( !GetNumber("Enter binning factor as positive integer number.", round(bin), bin ) ) exit(0)
}

number width,height
GetSize( img, width, height )

// Check that binning is smaller than any image dimension and exit script
// with an error dialog if not.
if ( ( bin > width ) || ( bin > height ) ) Throw( "Binning bigger than image dimension." )


// Create a Real 4-byte image with dimensions 1/n of the input image
// Note that the command expects integer values and will automatically truncate any
// number to interger. Hence width/bin will be the smallest suitable number
image BinImg := RealImage( "Binned ("+bin+"x)", 4 , width/bin, height/bin )
ShowImage( BinImg )

// Check if the binning will account for all pixels or warn the user otherwise.
if ( mod(width,bin) || mod(height,bin) )
	OKDialog( "Warning: The chosen binning will miss out some intensity. (No integer factor of width or height)")

// Loop over binning number in X&Y and sum dataset with accordingly extracted subdata.
for ( number ix = 0; ix<bin; ix++ )
{
	for ( number iy = 0; iy<bin; iy++ )
	{
		// Slice2 addresses a 2D subdata set of img. 
		// The first number triplet specifies a sampling starting point as X/Y/Z
		// the second number triplet specifies a sampling direction, sampling lenght and sampling step size for the first output dimension 
		// the thire number triplet specifies a sampling direction, sampling lenght and sampling step size for the second output dimension
		BinImg += slice2( img, ix, iy, 0, 0, width/bin, bin, 1, height/bin, bin )
	}
}