Watersheds Segmentation

In [1]:
import matplotlib.pyplot as plt
%matplotlib inline
import SimpleITK as sitk
from myshow import myshow, myshow3d

# Download data to work on
%run update_path_to_download_script
from downloaddata import fetch_data as fdata
In [2]:
img = sitk.ReadImage(fdata("cthead1.png"))
myshow(img)
Fetching cthead1.png

Gradient Watersheds Segmentation

In [3]:
sigma=img.GetSpacing()[0]
level=4
In [4]:
feature_img = sitk.GradientMagnitude(img)
myshow(feature_img, "Edge Features")
In [5]:
ws_img = sitk.MorphologicalWatershed(feature_img, level=0, markWatershedLine=True, fullyConnected=False)
myshow(sitk.LabelToRGB(ws_img), "Watershed Over Segmentation")
In [6]:
from ipywidgets import interact, interactive, FloatSlider

def callback(feature_img,*args, **kwargs):
    ws_img = sitk.MorphologicalWatershed(feature_img,*args, **kwargs)
    
    myshow(sitk.LabelToRGB(ws_img), "Watershed Segmentation")
    
interact(lambda **kwargs: callback(feature_img, **kwargs),
             markWatershedLine=True,
             fullyConnected=False,
             level=FloatSlider(min=0, max=255, step=0.1, value=4.0) )
Out[6]:
<function __main__.<lambda>>

Segmentation From Markers

In [7]:
min_img = sitk.RegionalMinima(feature_img, backgroundValue=0, foregroundValue=1.0, fullyConnected=False, flatIsMinima=True)
marker_img = sitk.ConnectedComponent(min_img)
myshow(sitk.LabelToRGB(marker_img), "Too many local minima markers")
In [8]:
ws = sitk.MorphologicalWatershedFromMarkers(feature_img, marker_img, markWatershedLine=True, fullyConnected=False)
myshow(sitk.LabelToRGB(ws), "Watershed Oversegmentation from markers")
In [9]:
pt = [60,60]
idx = img.TransformPhysicalPointToIndex(pt)
marker_img *= 0
marker_img[0,0] = 1
marker_img[idx] = 2

ws = sitk.MorphologicalWatershedFromMarkers(feature_img, marker_img, markWatershedLine=True, fullyConnected=False)
myshow(sitk.LabelOverlay(img, ws, opacity=.2), "Watershed Oversegmentation from manual markers")

Binary Watersheds for Object Separation

In [10]:
rgb_img = sitk.ReadImage(fdata("coins.png"))
myshow(rgb_img, "coins.png")
img = sitk.VectorIndexSelectionCast(rgb_img,1)
myshow(img, "Green Coins")
Fetching coins.png