Is there a way of programatically detecting whether a photograph is in focus?

StackOverflow https://stackoverflow.com/questions/3793519

  •  05-10-2019
  •  | 
  •  

سؤال

If I were building a web service that used a number of photos to illustrate a service, it would be useful to actually detect whether photos are in focus or not.

Is there any way of doing this programatically? (Even better, is there an open source implementation of such a routine?)

هل كانت مفيدة؟

المحلول

How do you know it is in focus? You recognize the object, of course, but more generally, because it has detail. Detail, typically, means drastic change in color over a short range of pixels. I'm sure you can find a lot of edge detection algorithms out there via google. Without giving it much thought:

edgePixelCount = 0;

for each pixel in image
{
    mixed = pixel.red + pixel.blue + pixel.green;
    for each adjacentPixel in image.adjacentPixels(pixel)
    {
        adjacentMixed = 
           adjacentPixel.red + 
           adjacentPixel.blue + 
           adjacentPixel.green;
        if ( abs ( adjacentMixed - mixed ) > EDGE_DETECTION_THRESHOLD )
        {
             edgePixelCount++;
             break;
        }
    }
}

if (edgePixelCount > NUMBER_OF_EDGE_PIXELS_THRESHOLD)
{
     focused = true;
}

Note: you'd probably need to use "adjacent pixels" with some distance, not just immediate edge pixels. Even in focus, high res images could often have gradients.

نصائح أخرى

Look into real edge detection methods - using laplacian filters, guassian filters, LoG (laplacian of gaussian), etc. These methods are much more tweakable to fit your specific cases than PatrickV's simple (albeit elegant) method.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top