Label image regionsΒΆ

This example shows how to segment an image with image labelling. The following steps are applied:

  1. Thresholding with automatic Otsu method
  2. Close small holes with binary closing
  3. Remove artifacts touching image border
  4. Measure image regions to filter small objects
../_images/plot_label_1.png

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

from skimage import data
from skimage.filter import threshold_otsu
from skimage.segmentation import clear_border
from skimage.morphology import label, closing, square
from skimage.measure import regionprops
from skimage.color import label2rgb


image = data.coins()[50:-50, 50:-50]

# apply threshold
thresh = threshold_otsu(image)
bw = closing(image > thresh, square(3))

# remove artifacts connected to image border
cleared = bw.copy()
clear_border(cleared)

# label image regions
label_image = label(cleared)
borders = np.logical_xor(bw, cleared)
label_image[borders] = -1
image_label_overlay = label2rgb(label_image, image=image)

fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
ax.imshow(image_label_overlay)

for region in regionprops(label_image):

    # skip small images
    if region.area < 100:
        continue

    # draw rectangle around segmented coins
    minr, minc, maxr, maxc = region.bbox
    rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
                              fill=False, edgecolor='red', linewidth=2)
    ax.add_patch(rect)

plt.show()

STDOUT


        

STDERR


        

Python source code: download (generated using skimage 0.11dev)

IPython Notebook: download (generated using skimage 0.11dev)

aW1wb3J0IG51bXB5IGFzIG5wCmltcG9ydCBtYXRwbG90bGliLnB5cGxvdCBhcyBwbHQKaW1wb3J0IG1hdHBsb3RsaWIucGF0Y2hlcyBhcyBtcGF0Y2hlcwoKZnJvbSBza2ltYWdlIGltcG9ydCBkYXRhCmZyb20gc2tpbWFnZS5maWx0ZXIgaW1wb3J0IHRocmVzaG9sZF9vdHN1CmZyb20gc2tpbWFnZS5zZWdtZW50YXRpb24gaW1wb3J0IGNsZWFyX2JvcmRlcgpmcm9tIHNraW1hZ2UubW9ycGhvbG9neSBpbXBvcnQgbGFiZWwsIGNsb3NpbmcsIHNxdWFyZQpmcm9tIHNraW1hZ2UubWVhc3VyZSBpbXBvcnQgcmVn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