%matplotlib inline
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage as ndi
from skimage import io
from skimage.segmentation import watershed
from skimage.feature import peak_local_max
from skimage.filters import threshold_otsu
%matplotlib inline
Perform some image smoothing to reduce image noise
image = io.imread("../images/nuclei-dapi.tif")
threshold = threshold_otsu(image)
print(threshold)
binary = ~(image <= threshold)
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12, 12))
ax[0].imshow(image, cmap='gray')
ax[0].set_title('Original Image')
ax[1].imshow(binary, cmap='gray')
ax[1].set_title('Binary Image')
plt.show()
distance = ndi.distance_transform_edt(binary)
threshold_m = 1.5*threshold_otsu(distance)
footprintsize = 31
coords = peak_local_max(distance, threshold_abs=threshold_m,
footprint=np.ones((footprintsize, footprintsize)), labels=image)
mask = np.zeros(distance.shape, dtype=bool)
print(coords.shape)
mask[tuple(coords.T)] = True
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12, 12))
ax[0].imshow(-distance, cmap='gray')
ax[0].set_title('Distance Transform')
ax[1].imshow(mask, cmap='gray')
ax[1].set_title('Markers')
plt.show()
markers, _ = ndi.label(mask)
labels1 = watershed(-distance, markers, mask=binary, compactness=0)
labels2 = watershed(-distance, markers, mask=binary, compactness=.01)
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12, 12))
ax[0].imshow(labels1)
ax[0].set_title('Watershed (compactness=0)')
ax[1].imshow(labels2)
ax[1].set_title('Watershed (compactness=0.01)')
plt.show()