Skip to content

Instantly share code, notes, and snippets.



Created Apr 14, 2017
What would you like to do?
Image analysis script for finding and visualising the areas of an image that are in focus.
from PIL import Image
from scipy import ndimage
import numpy as np
def getVar(im, sigma = 4.0):
'''Identifies & highlights areas of image fname with high pixel intensity variance (focus)'''
imbw = im.convert("F") # Convert im to greyscale array
arrbw = np.array(imbw)
sub_mean = ndimage.gaussian_filter(arrbw, sigma) # Calculate variance in area around each pixel
sub_sqr_mean = ndimage.gaussian_filter(arrbw**2, sigma)
sub_var = np.sqrt(sub_sqr_mean - sub_mean**2)
def scaleFocus(sub_var): return(sub_var/sub_var.max())
def showFocus(sub_var):
'''Visualise focus as white image with dark areas corresponding to demonstrably sharp focus'''
focus = scaleFocus(sub_var)
focus_arr = np.array(np.round(255.0 * (1.0 - focus)),dtype=np.uint8)
focus_im = Image.fromarray(focus_arr)
def maskImage(im,sub_var):
'''Visualise focus by masking original image according to pixel variance. Generates bright and dark versions.'''
focus = scaleFocus(sub_var)
arr = np.array(im)
arrbgrnd = np.copy(arr)
arrbgrnd[:,:,:] = 255
arr_dark = np.array(np.round(arr * focus[:,:,None]),dtype=np.uint8)
arr_bright = np.array(np.round((1 - focus[:,:,None]) * arrbgrnd + focus[:,:,None]*arr),dtype=np.uint8)
hilite_dark = Image.fromarray(arr_dark)
hilite_bright = Image.fromarray(arr_bright)
return({"bright":hilite_bright, "dark":hilite_dark})
def makeComposite(im, focus_im, masked_ims):
'''Build a 2x2 preview of original image, focus visualisation and bright & dark mask visualisations'''
ims ='RGB', (im.size[0]*2, im.size[1]*2))
ims.paste(im, (0,0))
if __name__ == "__main__":
import os
from urllib.request import urlretrieve # Python 3
except ImportError:
from urllib import urlretrieve # Python 2
fnames_hidef = {
for fname in fnames_hidef.keys():
if (not os.path.exists(fname)): urlretrieve(fnames_hidef[fname], fname)
im =
var = getVar(im,2.0)
focus_im = showFocus(var)
mask_im = maskImage(im,var)
makeComposite(im, focus_im, mask_im).save("composite_"+fname)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.