Skeleton extraction and watershed algorithm of Python Digital image processing

Source: Internet
Author: User
This article mainly introduced the Python Digital image processing skeleton extraction and the watershed algorithm, now shares to everybody, also gives everybody to make a reference. Come and see it together.

Skeleton extraction and watershed algorithm also belong to the morphological processing category, which are placed in the morphology sub-module.

1. Skeleton Extraction

Skeleton extraction, also called binary image refinement. This algorithm can refine a connected area into a pixel width for feature extraction and target topology representation.

The morphology submodule provides two functions for skeleton extraction, namely the skeletonize () function and the Medial_axis () function. Let's look at the Skeletonize () function first.

The format is:skimage.morphology. skeletonize (image)

Both the input and output are a two-value image.

Example 1:

From skimage import Morphology,drawimport numpy as Npimport Matplotlib.pyplot as plt# creates a binary image for testing image = Np.zeros ((400, 40 0)) #生成目标对象1 (White U-shape) image[10:-10, 10:100] = 1image[-100:-10, 10:-10] = 1image[10:-10, -100:-10] = # Generate target object 2 (x type) rs, cs = draw. Line (+, 280, j) for I in range: Image[rs + I, cs] = 1rs, cs = Draw.line (ten,, 280) for I in range: I Mage[rs + I, cs] = # Generate target object 3 (o type) ir, IC = np.indices (image.shape) circle1 = (ic-135) **2 + (ir-150) **2 < 30**2circle2 = (ic-135) **2 + (ir-150) **2 < 20**2image[circle1] = 1image[circle2] = 0# implement skeleton algorithm skeleton =morphology.skeletonize (imag e) #显示结果fig, (ax1, ax2) = Plt.subplots (Nrows=1, ncols=2, figsize= (8, 4)) ax1.imshow (image, Cmap=plt.cm.gray) Ax1.axis (' Off ') ax1.set_title (' original ', fontsize=20) ax2.imshow (skeleton, Cmap=plt.cm.gray) ax2.axis (' Off ') ax2.set_title (' Skeleton ', fontsize=20) fig.tight_layout () plt.show ()

Create a test image with three target objects, respectively, to extract the skeleton, the results are as follows:

Example 2: Skeleton extraction using horse pictures from the system

From skimage import Morphology,data,colorimport Matplotlib.pyplot as Pltimage=color.rgb2gray (Data.horse ()) image=1- Image #反相 # Implementation skeleton algorithm skeleton =morphology.skeletonize (image) #显示结果fig, (ax1, ax2) = Plt.subplots (Nrows=1, ncols=2, figsize= ( 8, 4)) ax1.imshow (image, Cmap=plt.cm.gray) ax1.axis (' Off ') ax1.set_title (' original ', fontsize=20) ax2.imshow (skeleton , Cmap=plt.cm.gray) Ax2.axis (' Off ') ax2.set_title (' Skeleton ', fontsize=20) fig.tight_layout () plt.show ()

Medial_axis is the meaning of the middle axis, the width of the target object is calculated using the Medium axis transformation method (1 value), in the form of:

skimage.morphology. Medial_axis (image,mask=none,return_distance=false)

Mask: Masks. The default is None, and if given a mask, the pixel value within the mask executes the skeleton algorithm.

The Return_distance:bool type value, which defaults to false. If true, the distance transform value is also returned, in addition to the skeleton. The distance here refers to the distance between all the points on the middle axis and the background points.

Import NumPy as Npimport scipy.ndimage as Ndifrom skimage import morphologyimport matplotlib.pyplot as plt# write a function to generate the test image de F microstructure (l=256): n = 5 x, y = np.ogrid[0:l, 0:l] mask = Np.zeros ((l, l)) generator = Np.random.RandomState (1) poin TS = L * Generator.rand (2, n**2) mask[(Points[0]). Astype (Np.int), (Points[1]). Astype (np.int)] = 1 mask = ndi.gaussian_filt ER (mask, sigma=l/(4.*n)) return mask > Mask.mean () data = microstructure (l=64) #生成测试图像 # Calculates the axis and distance transform values Skel, distance = Morphology.medial_axis (data, return_distance=true) #中轴上的点到背景像素点的距离dist_on_skel = distance * Skelfig, (ax1, ax2) = Plt.subplots (1, 2, figsize= (8, 4)) Ax1.imshow (data, Cmap=plt.cm.gray, interpolation= ' nearest ') #用光谱色显示中轴ax2. Imshow ( Dist_on_skel, cmap=plt.cm.spectral, interpolation= ' nearest ') ax2.contour (data, [0.5], colors= ' W ') #显示轮廓线fig. Tight_ Layout () Plt.show ()

2. Watershed algorithm

The watershed is geographically defined as a ridge in which water usually flows along the sides of the ridge to a different "catchment basin". Watershed algorithm is a classical algorithm for image segmentation, which is based on the topological theory of mathematical morphology segmentation method. If the target objects in the image are linked together, it is more difficult to split up, and the watershed algorithm is often used to deal with such problems, usually with better results.

The watershed algorithm can be combined with distance transform to find "catchment basin" and "watershed boundary", so as to divide the image. The distance transformation of a binary image is the distance from each pixel to the nearest 0-point pixel, and we can use the SCIPY package to calculate the distance transform.

In the following example, you need to separate the two overlapping circles. We first calculate the distance between these white pixels on the circle and the pixels of the black background, select the maximum value in the distance transform as the initial mark point (or the minimum if it is reversed), and the larger of the two basins that begin with these marks, the greater the number of sinks, and the final intersection of the ridges. Disconnected from the ridge, we got two separate circles.

Example 1: Fractal Ridge image Segmentation based on distance transformation

Import NumPy as Npimport Matplotlib.pyplot as Pltfrom scipy import ndimage as Ndifrom skimage import morphology,feature# Create Two images with overlapping circles x, y = np.indices ((x, x)) x1, y1, x2, y2 =, +, 52R1, r2 = +, 20mask_circle1 = (x-x1) **2 + (y-y1) * * 2 < R1**2mask_circle2 = (x-x2) **2 + (y-y2) **2 < R2**2image = Np.logical_or (Mask_circle1, Mask_circle2) #现在我们用分水岭算 Method separates two round distance = Ndi.distance_transform_edt (image) #距离变换local_maxi =feature.peak_local_max (distance, Indices=false, Footprint=np.ones ((3, 3)), labels=image) #寻找峰值markers = Ndi.label (Local_maxi) [0] #初始标记点labels =morphology.watershed ( -distance, Markers, mask=image) #基于距离变换的分水岭算法fig, axes = Plt.subplots (nrows=2, ncols=2, figsize= (8, 8)) axes = Axes.ravel ( ) ax0, Ax1, ax2, ax3 = axesax0.imshow (image, Cmap=plt.cm.gray, interpolation= ' nearest ') Ax0.set_title ("Original") Ax1.imshow (-distance, Cmap=plt.cm.jet, interpolation= ' nearest ') ax1.set_title ("Distance") ax2.imshow (markers, cmap= Plt.cm.spectral, interpolation= ' nearest ') Ax2.set_tiTle ("Markers") ax3.imshow (labels, cmap=plt.cm.spectral, interpolation= ' nearest ') Ax3.set_title ("segmented") for Ax in Axes:ax.axis (' Off ') fig.tight_layout () plt.show ()

Watershed algorithms can also be combined with gradients to achieve image segmentation. A general gradient image has a higher pixel value at the edge and a lower pixel value elsewhere, ideally at the edge of the ridge. Therefore, we can find the ridge according to the gradient.

Example 2: Gradient-based watershed image segmentation

Import Matplotlib.pyplot as Pltfrom scipy import ndimage as Ndifrom skimage import morphology,color,data,filterimage =colo R.rgb2gray (Data.camera ()) denoised = Filter.rank.median (Image, Morphology.disk (2)) #过滤噪声 # The gradient value below 10 as the start mark point markers = Filter.rank.gradient (denoised, Morphology.disk (5)) <10markers = Ndi.label (markers) [0]gradient = Filter.rank.gradient (denoised, Morphology.disk (2)) #计算梯度labels =morphology.watershed (gradient, markers, mask=image) #基于梯度的分水岭算法fig, axes = Plt.subplots (nrows=2, ncols=2, figsize= (6, 6)) axes = Axes.ravel () ax0, Ax1, ax2, ax3 = Axesax0.imsho W (image, Cmap=plt.cm.gray, interpolation= ' nearest ') Ax0.set_title ("Original") ax1.imshow (gradient, cmap= Plt.cm.spectral, interpolation= ' nearest ') Ax1.set_title ("Gradient") ax2.imshow (markers, Cmap=plt.cm.spectral, interpolation= ' nearest ') Ax2.set_title ("Markers") ax3.imshow (labels, cmap=plt.cm.spectral, interpolation= ' nearest ') ) Ax3.set_title ("segmented") for Ax in Axes:ax.axis (' Off ') fig.tight_layout () plt.show ()

Related recommendations:

Advanced morphological processing of python digital image processing

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.