
// Script function: Calculate a ROI area above a given intensity-threshold on the image
// Requirement: Open an image and then draw a ROI on it

// 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 GlobalSinoImage
 
if ( !GetFrontImage( GlobalSinoImage ) )
Throw( "Please open an image and draw a rectangle ROI" )

GlobalSinoImage:=getfrontimage()

ImageDisplay EMImage=GlobalSinoImage.ImageGetImageDisplay(0)

if( 1 !=  EMImage.ImageDisplayCountROIs())
Throw( "Please draw a rectangle ROI" )

number EMxScale, EMyScale
GetScale(GlobalSinoImage, EMxScale, EMyScale)
 
ImageDisplay EMImageDisplay=GlobalSinoImage.ImageGetImageDisplay(0)
ROI EMROI=EMImageDisplay.ImageDisplayGetROI(0)

image EMROIImage=GlobalSinoImage[]
ShowImage(EMROIImage)

ImageCopyCalibrationFrom(EMROIImage, GlobalSinoImage)

string EMImageName
GetName(GlobalSinoImage, EMImageName)
ImageDisplay EMROIDisplay=EMROIImage.ImageGetImageDisplay(0)
EMROIDisplay.ApplyDataBar()
string GlobalSinoImageName="ROI from " + EMImageName
SetName(EMROIImage, GlobalSinoImageName)

number EMValue

TagGroup GlobalSino, EMItems
GlobalSino = DLGCreateDialog( "Please confirm your own threshold", EMItems )
 
TagGroup MyNumber1, MyNumber2, MyNumber3

Number GlobalSinoMax = max(EMROIImage)
Number GlobalSinoMin = min(EMROIImage)
  
EMItems.DLGAddElement( DLGCreateRealField( "Maximum intensity:               ", MyNumber1, GlobalSinoMax, 10, 3 ) )       
EMItems.DLGAddElement( DLGCreateRealField( "Minimum intensity:                ", MyNumber2, GlobalSinoMin, 10, 5 ) )       

number GlobalSionMedium = (GlobalSinoMax + GlobalSinoMin)/2
EMItems.DLGAddElement( DLGCreateRealField( "My threshold:                       ", MyNumber3, GlobalSionMedium, 10, 8 ) )    

  
if ( !Alloc( UIframe ).Init( GlobalSino ).Pose() ) exit (0)


number EMxSize, EMySize, EMx, EMy // 
getsize(EMROIImage, EMxSize, EMySize) //

number EMTop, EMLeft, EMBottom, EMRight //
number EMROIUnitWidth, EMROIUnitHeight //


ROIGetRectangle(EMROI, EMTop, EMLeft, EMBottom, EMRight)
EMROIUnitWidth=(EMRight-EMLeft)*EMxScale
EMROIUnitHeight=(EMBottom-EMTop)*EMyScale

for (EMy = 0; EMy < EMySize; EMy++) {
for (EMx = 0; EMx < EMxSize; EMx++) {
EMValue = GetPixel(EMROIImage, EMx, EMy);
if (EMValue > MyNumber3.DLGGetValue())
EMValue = 1
else
EMValue = 0
SetPixel(EMROIImage, EMx, EMy, EMValue)
}
}

number EMPixelArea
EMPixelArea = EMxScale*EMyScale*sum (EMROIImage)
String EMLengthUnits = GetUnitString(EMROIImage)
Result ("\n" + EMPixelArea + "\t" + EMLengthUnits+"^2")

EMROIImage.SetName("Included area from " + EMROIImage.GetName())
ShowImage(EMROIImage)
