program AutoThreshold ; { Robust Automatic Threshold Selector (RATS) } { Copyright © April 1998, Digital Optics Ltd } { This module automatically computes a threshold intensity for the active image and creates a binary copy. The technique works best if the image histogram is roughly bimodal. If there are multiple peaks in the histogram RATS tends to threshold at the first peak. } { Auto thresholding code is contained in the RATS() procedure, which can be triggered using the toolbar button or by other modules via DDE } { The calls to Filter() used here are compatible with V++ 4.0.5.68 or later. With earlier versions, insert a scale factor parameter of 1. Better yet, download a free update to the latest version! } procedure RATS ; button btn_Text,'RATS|Auto threshold' ; dde 'Rats' ; var Image1,Image2 ; hMask,vMask ; hDeriv,vDeriv ; gtMask ; eij,hij ; SumEij ; Seg ; zMask,SE ; begin GetActiveImage( Image1 ) ; if IsImage( Image1 ) then begin { convert } Image2 := longint( Image1 ) ; { mask any zero pixels } zMask := Image2 <> 0; SE := CreateImage(binary,3,3); SE := 1 ; ZMask := Erode( zMask,SE,1,1 ) ; { create derivative masks } hMask := CreateArray( typ_Longint,3,1 ) ; hMask[0,0] := -1 ; hMask[1,0] := 0 ; hMask[2,0] := +1 ; vMask := CreateArray( typ_Longint,1,3 ) ; vMask[0,0] := -1 ; vMask[0,1] := 0 ; vMask[0,2] := +1 ; { calculate derivative images } hDeriv := Filter( Image2,hMask,1 ) ; // modified for 4.0.5.68 and later vDeriv := Filter( Image2,vMask,1 ) ; // modified for 4.0.5.68 and later { calculate maximum derivative } gtMask := vDeriv > hDeriv ; eij := Mask( vDeriv,gtMask ) + Mask( hDeriv,not( gtMask ) ) ; { calculate h(i,j) } hij := Image2 * eij ; { threshold } SumEij := SumOf( eij ) ; if SumEij <> 0 then begin Seg := Image2 >= SumOf( hij ) / SumEij ; Show( Seg ) ; end else WriteError( 'Unable to determine threshold' ) ; end; end; begin end.