Comparing edge-based and region-based segmentation¶
In this example, we will see how to segment objects from a background. We use
coins image from
skimage.data, which shows several coins outlined
against a darker background.
import numpy as np import matplotlib.pyplot as plt from skimage import data from skimage.exposure import histogram coins = data.coins() hist, hist_centers = histogram(coins) fig, axes = plt.subplots(1, 2, figsize=(8, 3)) axes.imshow(coins, cmap=plt.cm.gray) axes.axis('off') axes.plot(hist_centers, hist, lw=2) axes.set_title('histogram of gray values')
A simple way to segment the coins is to choose a threshold based on the histogram of gray values. Unfortunately, thresholding this image gives a binary image that either misses significant parts of the coins or merges parts of the background with the coins:
Next, we try to delineate the contours of the coins using edge-based segmentation. To do this, we first get the edges of features using the Canny edge-detector.
These contours are then filled using mathematical morphology.
Small spurious objects are easily removed by setting a minimum size for valid objects.
However, this method is not very robust, since contours that are not perfectly closed are not filled correctly, as is the case for one unfilled coin above.
We therefore try a region-based method using the watershed transform. First, we find an elevation map using the Sobel gradient of the image.
Next we find markers of the background and the coins based on the extreme parts of the histogram of gray values.
Finally, we use the watershed transform to fill regions of the elevation map starting from the markers determined above:
This last method works even better, and the coins can be segmented and labeled individually.
from skimage.color import label2rgb segmentation = ndi.binary_fill_holes(segmentation - 1) labeled_coins, _ = ndi.label(segmentation) image_label_overlay = label2rgb(labeled_coins, image=coins) fig, axes = plt.subplots(1, 2, figsize=(8, 3), sharey=True) axes.imshow(coins, cmap=plt.cm.gray) axes.contour(segmentation, [0.5], linewidths=1.2, colors='y') axes.imshow(image_label_overlay) for a in axes: a.axis('off') plt.tight_layout() plt.show()
Total running time of the script: ( 0 minutes 0.994 seconds)