In [1]:
%run ../../common.ipynb
Populating the interactive namespace from numpy and matplotlib
In [2]:
from skimage.morphology import watershed
In [3]:
>>> from skimage.morphology import watershed
>>> from skimage.feature import peak_local_max
>>> from skimage.measure import label
>>>
>>> # Generate an initial image with two overlapping circles
>>> x, y = np.indices((80, 80))
>>> x1, y1, x2, y2 = 28, 28, 44, 52
>>> r1, r2 = 16, 20
>>> mask_circle1 = (x - x1)**2 + (y - y1)**2 < r1**2
>>> mask_circle2 = (x - x2)**2 + (y - y2)**2 < r2**2
>>> # Now we want to separate the two objects in image
>>> # Generate the markers as local maxima of the distance
>>> # to the background
>>> from scipy import ndimage
>>> distance = ndimage.distance_transform_edt(image)
>>> local_maxi = peak_local_max(distance, indices=False, footprint=np.ones((3, 3)),labels=image)
>>> markers = label(local_maxi)
>>> labels_ws = watershed(-distance, markers, mask=image)
/Users/arve/.virtualenvs/3.4/lib/python3.4/site-packages/skimage/morphology/watershed.py:214: FutureWarning: comparison to None will result in an elementwise object comparison in the future.
In [4]:
gimshow(labels_ws)
In [5]:
local_max = peak_local_max(image, threshold_rel=0.2, min_distance=10, indices=False)
markers = label(local_max)
image_ws = watershed(-image, markers)
In [6]:
imshow(image_ws)
image_ws.dtype
Out[6]:
dtype('int64')

Lets save it with colors. We need to convert it to uint32 and reshape it to contain a color dimension.

In [7]:
# scale it to 3 colors * 8 bit
image_ws_rgb = image_ws / image_ws.max() * 2**24
image_ws_rgb = image_ws_rgb.astype(np.uint32)
# reshape magic, tuple concat: (1,2) + (3,) = (1,2,3)
image_ws_rgb = image_ws_rgb.view(np.uint8).reshape(image.shape + (4,))
# lets get rid of unused color dimension (alpha)
image_ws_rgb = image_ws_rgb[:,:,0:3]
imsave('watershed.png', image_ws_rgb)
Image('watershed.png')
Out[7]:

Lets save it as grayscale also.

In [9]:
imsave('watershed_gray.png', scale(image_ws))
Image('watershed_gray.png')
Out[9]: