mirror of
https://github.com/wassname/scikit-image.git
synced 2026-06-28 01:46:21 +08:00
58 lines
1.4 KiB
Python
58 lines
1.4 KiB
Python
"""
|
|
===================
|
|
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
|
|
|
|
"""
|
|
|
|
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
|
|
|
|
|
|
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
|
|
|
|
fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
|
|
ax.imshow(label_image, cmap='jet')
|
|
|
|
for region in regionprops(label_image, ['Area', 'BoundingBox']):
|
|
|
|
# skip small images
|
|
if region['Area'] < 100:
|
|
continue
|
|
|
|
# draw rectangle around segmented coins
|
|
minr, minc, maxr, maxc = region['BoundingBox']
|
|
rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
|
|
fill=False, edgecolor='red', linewidth=2)
|
|
ax.add_patch(rect)
|
|
|
|
plt.show()
|