in order to perform any automatic correction, you need two things: a image metric, and an optimization algorithm. In the case of focusing, a good metric can be the edge contrast, often referred to as acutance (https://en.wikipedia.org/wiki/Acutance), which is, in simple words, the mean square difference in intensity between adjacent pixels. Other metrics could be the variance of the image, or the high spatial frequency content of the image, computed through its fourier transform.
Once you have your metric, which is maximum (or minimum) when the image is on focus, you need an optimization algorithm. If you are not in a hurry, you can simply scan through the focus, compute the metric for many positions, and fit the curve with a polynomial (usually a parabola) to find the maximum. In alternative you can use more advanced algorithms such as stochastic gradient descent, or simplex optimization, in order to find your minimum in less iterations.
I hope this was useful, good luck with your experiment!
in order to perform any automatic correction, you need two things: a image metric, and an optimization algorithm. In the case of focusing, a good metric can be the edge contrast, often referred to as acutance (https://en.wikipedia.org/wiki/Acutance), which is, in simple words, the mean square difference in intensity between adjacent pixels. Other metrics could be the variance of the image, or the high spatial frequency content of the image, computed through its fourier transform.
Once you have your metric, which is maximum (or minimum) when the image is on focus, you need an optimization algorithm. If you are not in a hurry, you can simply scan through the focus, compute the metric for many positions, and fit the curve with a polynomial (usually a parabola) to find the maximum. In alternative you can use more advanced algorithms such as stochastic gradient descent, or simplex optimization, in order to find your minimum in less iterations.
I hope this was useful, good luck with your experiment!