Gradient Energy

The gradient energy of an image is computed by summing the squares of the differences between adjacent pixel values in the x- and y-directions over an entire image. The premise being that in general, a sharper image will have greater pixel-to-pixel contrast values. This technique is discussed in a paper, Focusing Techniques, by Subbarao, Choi, and Nizkad from the Department of Electrical Engineering, State University of New York at Stony Brook. This paper covers several focusing techniques with a mathematical proof of the soundness of each.

To calculate the gradient energy of an image you use a 3-pixel kernel as shown in the figure below.

Gradient energy kernel

xDiff and yDiff are the gradient magnitude values for a given pixel location in an image. The energy gradient score for an image is the sum of the squares of xDiff and yDiff normalized by the square of the image mean grey value, summed over the entire image. The focus position that produces the highest gradient energy score produces the sharpest image.