1""" 2========================================== 3Find the intersection of two segmentations 4========================================== 5 6When segmenting an image, you may want to combine multiple alternative 7segmentations. The :py:func:`skimage.segmentation.join_segmentations` 8function computes the join of two segmentations, in which a pixel is 9placed in the same segment if and only if it is in the same segment in 10*both* segmentations. 11 12""" 13import numpy as np 14import matplotlib.pyplot as plt 15 16from skimage.filters import sobel 17from skimage.measure import label 18from skimage.segmentation import slic, join_segmentations, watershed 19from skimage.color import label2rgb 20from skimage import data 21 22coins = data.coins() 23 24# Make segmentation using edge-detection and watershed. 25edges = sobel(coins) 26 27# Identify some background and foreground pixels from the intensity values. 28# These pixels are used as seeds for watershed. 29markers = np.zeros_like(coins) 30foreground, background = 1, 2 31markers[coins < 30.0] = background 32markers[coins > 150.0] = foreground 33 34ws = watershed(edges, markers) 35seg1 = label(ws == foreground) 36 37# Make segmentation using SLIC superpixels. 38seg2 = slic(coins, n_segments=117, max_num_iter=160, sigma=1, compactness=0.75, 39 channel_axis=None, start_label=0) 40 41# Combine the two. 42segj = join_segmentations(seg1, seg2) 43 44# Show the segmentations. 45fig, axes = plt.subplots(ncols=2, nrows=2, figsize=(9, 5), 46 sharex=True, sharey=True) 47ax = axes.ravel() 48ax[0].imshow(coins, cmap='gray') 49ax[0].set_title('Image') 50 51color1 = label2rgb(seg1, image=coins, bg_label=0) 52ax[1].imshow(color1) 53ax[1].set_title('Sobel+Watershed') 54 55color2 = label2rgb(seg2, image=coins, image_alpha=0.5, bg_label=-1) 56ax[2].imshow(color2) 57ax[2].set_title('SLIC superpixels') 58 59color3 = label2rgb(segj, image=coins, image_alpha=0.5, bg_label=-1) 60ax[3].imshow(color3) 61ax[3].set_title('Join') 62 63for a in ax: 64 a.axis('off') 65fig.tight_layout() 66plt.show() 67