Skip to content
Advertisement

Get In Focus Pixels of an Image

How to detect which pixels of an image are in focus compared to the blurry ones. Something like the ‘Focus Peaking’ feature lots of cameras have?

The idea is to color the pixels that are in focus so that it assists the user while clicking a picture. Looking for an implementation through Python.

Advertisement

Answer

You can find the edges, which are sharp or high contrast and then superimpose them onto the original image.

So, starting with this image:

enter image description here Credit: Rita Kochmarjova – Fotolia

You can do:

#!/usr/bin/env python3

import numpy as np
from PIL import Image, ImageFilter, ImageChops

# Open input image and make greyscale copy
image = Image.open('bulldog.jpg')
grey  = image.copy().convert('L')

# Find the edges
edges = grey.filter(ImageFilter.FIND_EDGES)
edges.save('edges.png')

# Draw the sharp edges in white over original
RGBedges = Image.merge('RGB',(edges,edges,edges))
image.paste(RGBedges, mask=edges)

# Save
image.save('result.png')

enter image description here

You can see the effect most clearly in the stones at water’s edge.

Here is the intermediate edges.png. You could dilate the white pixels somewhat, or threshold to make the in-focus parts more heavily defined.

enter image description here


Here it is with the edges dilated a little to make them more obvious:

#!/usr/bin/env python3

import numpy as np
from PIL import Image, ImageFilter
from skimage.morphology import dilation, square

# Open input image and make greyscale copy
image = Image.open('bulldog.jpg')
grey  = image.copy().convert('L')

# Find the edges
edges = grey.filter(ImageFilter.FIND_EDGES)

# Define a structuring element for dilation
selem = square(3)
fatedges = dilation(np.array(edges),selem)
fatedges = Image.fromarray(fatedges)
fatedges.save('edges.png')

# Draw the sharp edges in white over original
RGBedges = Image.merge('RGB',(fatedges,fatedges,fatedges))
image.paste(RGBedges, mask=fatedges)

# Save
image.save('result.png')

enter image description here


You can also do it in Terminal with ImageMagick without writing any code:

magick bulldog.jpg ( +clone -canny 0x1+10%+30% ) -compose overlay -composite  result.png

enter image description here

Or this, which is more similar to the Python:

magick bulldog.jpg ( +clone -canny 0x1+10%+30% ) -compose lighten -composite  result.png

enter image description here

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement