This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.
import numpy as np
import matplotlib.pyplot as plt
from skimage.data import coins
from skimage.filter import threshold_otsu
from skimage.segmentation import clear_border
from skimage.morphology import closing, square
from skimage.measure import regionprops, label
from skimage.color import lab2rgb
import matplotlib as mpl
%matplotlib inline
def show(img, cmap=None):
cmap = cmap or plt.cm.gray
plt.figure(figsize=(4,2));
plt.imshow(img, cmap=cmap);
plt.axis('off');
plt.show();
img = coins()
show(img)
threshold_otsu(img)
show(img>107)
from IPython.html import widgets
@widgets.interact(t=(10, 240))
def threshold(t):
show(img>t)
img_bin = clear_border(closing(img>120, square(5)))
show(img_bin)
label
function. This function detects the connected components in the image, and attributes a unique label to every component. Here, we color-code the labels in the binary image.labels = label(img_bin)
show(labels, cmap=plt.cm.rainbow)
regionprops
function allows us to retrieve specific properties of the components (here, the area and the bounding box).regions = regionprops(labels)
boxes = np.array([label['BoundingBox'] for label in regions
if label['Area'] > 100])
print("There are {0:d} coins.".format(len(boxes)))
plt.figure(figsize=(6,4));
plt.imshow(img, cmap=plt.cm.gray);
plt.axis('off');
xs = boxes[:,[1,3]].mean(axis=1)
ys = boxes[:,[0,2]].mean(axis=1)
for i, box in enumerate(boxes):
plt.text(xs[i]-5, ys[i]+5, str(i))
You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).
IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).