Created
September 6, 2016 23:19
-
-
Save TheNeuralBit/aa988bf56f53b37bdb28f60e5e965330 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
=================== | |
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 matplotlib.pyplot as plt | |
import matplotlib.patches as mpatches | |
from skimage import data | |
from skimage.filters import threshold_otsu | |
from skimage.segmentation import clear_border | |
from skimage.measure import label, regionprops | |
from skimage.morphology import closing, square | |
from skimage.color import label2rgb | |
from timeit import timeit | |
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 = clear_border(bw) | |
## time it | |
## prove that it works | |
iterations = 10000 | |
time = timeit("label(cleared)", setup="from __main__ import label, cleared", number=iterations) | |
print("Time: %.3fs for %d runs, %.3fms/run" % (time, iterations, time/iterations*1000)) | |
## prove that it works | |
# label image regions | |
label_image = label(cleared) | |
image_label_overlay = label2rgb(label_image, image=image) | |
fig, ax = plt.subplots(figsize=(10, 6)) | |
ax.imshow(image_label_overlay) | |
for region in regionprops(label_image): | |
# take regions with large enough areas | |
if region.area >= 100: | |
# 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) | |
ax.set_axis_off() | |
plt.tight_layout() | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Benchmark results on my laptop with python 3.5.1:
on master 92a38515ac7222aab5e606f9de46caf5f503a7bd
On PR#2282 branch 0525bb9b77e7e8e271534ffd4c6b07180f1ffa4f