import numpy as np from matplotlib import pyplot as plt, cm from skimage import io from scipy import ndimage as nd from skimage.filter import threshold_otsu from skimage.morphology import disk from skimage.color import rgb2gray from skimage import img_as_float from skimage.morphology import opening from skimage.morphology import remove_small_objects # needs skimage 0.9dev; comment out the following line if your version is earlier from skimage.color import label2rgb %cd ~/Downloads/ filename = 'P1.jpg' disk_size = 18 otsu_scale_factor = 1.45 %pylab inline pothole = io.imread(filename) gpot = img_as_float(rgb2gray(pothole)) plt.imshow(gpot, cmap=cm.gray) plt.show() t = threshold_otsu(gpot) * otsu_scale_factor s = disk(disk_size) tpot = gpot < t plt.imshow(tpot, cmap=cm.gray) plt.show() tpot_open = opening(tpot, s) plt.imshow(tpot_open, cmap=cm.gray) plt.show() objects = nd.label(tpot_open)[0] # label each connected region b = np.bincount(objects.ravel()) # find object sizes largest_object_size = sorted(b)[-2] # get second largest object pothole_object = remove_small_objects(tpot_open.astype(bool), largest_object_size - 1) plt.imshow(pothole_object) plt.show() pothole_object = nd.binary_fill_holes(pothole_object) plt.imshow(pothole_object) plt.show() found_pothole = label2rgb(pothole_object, pothole) plt.imshow(found_pothole) plt.show()