Here are two images of the same scene, one focused close and the other focused at a distance.
We can combine the in-focus parts of both photographs using the following procedure. First each input image is blurred.
Next, we subtract the blurred image from the original above it, and create an image that shows the magnitude of the difference. This image will be dark where the original image is smooth, and will be bright where the original image has edges. The strength of the edge information maps directly into the brightness of these edge images.
Now we compare the two edge images, and make an image that is black where the left image has more edge information, and is white where the right image has more edge information.
Finally, this is used to create an image with the best parts of each original image. Where the image above is black, pixels from the left image are used. Where the image above is white, pixels from the right image are used.
A simple extension of this technique can be used to combine the in-focus parts of any number of photographs.