Here's my favorite focus measurement in pseudocode:
Apply Prewitt filter to detect edges in image.
Use Quantify Image to get statistics for entire image. I have found that the Std. Dev. of the pixel intensities is a great focus indicator. The mean intensity also works pretty well.
To speed things up, I frequently reduce the image resolution. Extracting every other pixel in both directions gives you an image that is half the size and processes four times faster than the original image. Unless you have really, really fine details, this usually works just as well as the original image.
Bruce
Bruce Ammons
Ammons Engineering