Advanced morphological processing of python digital image processing

Source: Internet
Author: User
Tags list of attributes
This article mainly introduced the Python Digital Image processing advanced morphology processing, now shares to everybody, also gives everybody to make a reference. Come and see it together.

Morphological processing, in addition to the most basic expansion, corrosion, open/close operation, black/white hat processing, there are some more advanced applications, such as convex hull, connected area marker, delete Small block area.

1. Convex bag

Convex hull refers to a convex polygon, which contains all the white pixels in the image.

The functions are:

Skimage.morphology.convex_hull_image (image)

Input is a two value image, output a logical binary image. The point inside the convex hull is true, otherwise false

Cases:

Import Matplotlib.pyplot as Pltfrom skimage import data,color,morphology# Generate two value test image Img=color.rgb2gray (Data.horse ()) img = (img<0.5) *1chull = Morphology.convex_hull_image (img) #绘制轮廓fig, axes = Plt.subplots (1,2,figsize= (8,8)) ax0, ax1= Axes.ravel () ax0.imshow (Img,plt.cm.gray) ax0.set_title (' original image ') Ax1.imshow (Chull,plt.cm.gray) ax1.set_ Title (' Convex_hull image ')

Convex_hull_image () is to treat all the objects in the picture as a whole, so that only one of the smallest convex polygons is computed. If you have more than one target object in the diagram, each object needs to calculate a minimum convex polygon, you need to use the Convex_hull_object () function.

function format:skimage.morphology. Convex_hull_object (image,neighbors=8)

Input parameters image is a binary image, neighbors indicates whether it is 4 connected or 8 connected, and the default is 8 connectivity.

Cases:

Import Matplotlib.pyplot as Pltfrom skimage import data,color,morphology,feature# generates a two value test image Img=color.rgb2gray ( Data.coins ()) #检测canny边缘, get two value picture Edgs=feature.canny (IMG, sigma=3, low_threshold=10, high_threshold=50) Chull = Morphology.convex_hull_object (EDGs) #绘制轮廓fig, axes = Plt.subplots (1,2,figsize= (8,8)) ax0, ax1= axes.ravel () ax0.imshow (Edgs,plt.cm.gray) Ax0.set_title (' many objects ') ax1.imshow (Chull,plt.cm.gray) ax1.set_title (' Convex_hull image ') Plt.show ()

2. Connected area marking

In a binary image, if the two pixels are adjacent and the values are the same (0 or the same as 1), then the two pixels are considered to be in an interconnected area. All pixels in the same connected area are labeled with the same value, which is called the connected area marker. When judging whether two pixels are contiguous, we usually use 4-connected or 8-connected judgments. In the image, the smallest units are pixels, with 8 contiguous pixels around each pixel, and there are 2 common adjacency relationships: 4 adjacency and 8 adjacency. 4 adjacency altogether 4 points, i.e. up and down, as shown in the figure on the left. 8 The adjacent points have a total of 8 points, including the point at the diagonal, as shown in the image on the right.

In the Skimage package, we use the label () function under the measure sub-module to implement the connected area tag.

function format:

Skimage.measure.label (Image,connectivity=none)

The image in the parameter represents the two-value images that need to be processed, connectivity represents the mode of the connection, 1 represents 4 adjacency, and 2 represents 8 adjacency.

Prints an array of tokens (labels), starting with the 0 tag.

Import NumPy as Npimport scipy.ndimage as Ndifrom skimage import measure,colorimport matplotlib.pyplot as plt# write a function to generate the original two Value Image def microstructure (l=256):  n = 5  x, y = np.ogrid[0:l, 0:l] #生成网络  mask = Np.zeros ((l, L))  generator = NP . Random. Randomstate (1) #随机数种子  points = L * Generator.rand (2, n**2)  mask[(Points[0]). Astype (Np.int), (Points[1]). Astype (np.int)] = 1  mask = ndi.gaussian_filter (Mask, sigma=l/(4.*n)) #高斯滤波  return mask > Mask.mean () data = Mic Rostructure (l=128) * * #生成测试图片labels =measure.label (data,connectivity=2) #8连通区域标记dst =color.label2rgb (labels) # Displays different colors according to different tags print (' Regions number: ', Labels.max () +1) #显示连通区域块数 (starting from 0 marks) FIG, (ax1, ax2) = Plt.subplots (1, 2, figsize= (8 , 4)) Ax1.imshow (data, Plt.cm.gray, interpolation= ' nearest ') Ax1.axis (' Off ') ax2.imshow (dst,interpolation= ' nearest ') Ax2.axis (' Off ') fig.tight_layout () plt.show ()

In code, where you multiply by 1, you can quickly convert a bool array to an int array.

The result has 10 connected regions, labeled 0-9

If you want to operate each connected area separately, such as calculating area, external rectangle, convex hull area, etc., you need to call the Regionprops () function of the measure submodule. The function is in the following format:

Skimage.measure.regionprops (Label_image)

Returns the list of attributes for all connected chunks, and the list of commonly used attributes is the following table:


Property name Type Describe
Area Int Total number of pixel points in the region
Bbox Tuple Bounding box (Min_row, Min_col, Max_row, Max_col)
Centroid Array Centroid coordinates
Convex_area Int Total number of pixel points in convex hull
Convex_image Ndarray Convex hull of the same size as the bounding box
Coords Ndarray Pixel coordinates in the area.
Eccentricity Float Off heart rate
Equivalent_diameter Float The diameter of the circle with the same area area
Euler_number Int Region Euler number
Extent Float Ratio of area area to boundary external box area
Filled_area Int Total number of pixel points populated between the area and the Add-in box
Perimeter Float Area perimeter
Label Int Zone Markers

3, delete the small block area

Sometimes we just need some big chunks, those scattered, small chunks, we need to delete them, we can use the remove_small_objects () function of the morphology submodule.

function format:skimage.morphology. remove_small_objects (ar,min_size=64,connectivity=1,in_place=false)

Parameters:

AR: An array of bool types to be manipulated.

Min_size: The minimum connected area size, which is smaller than the size, will be removed. The default is 64.

Connectivity: adjacency mode, 1 means 4 adjacency, 2 means 8 adjacency

The In_place:bool type value, if true, indicates that the small area is deleted directly in the input image, otherwise it is copied and then deleted. The default is False.

Returns a two-value image that has deleted a small chunk area.

Import NumPy as Npimport scipy.ndimage as Ndifrom skimage import morphologyimport matplotlib.pyplot as plt# write a function to generate the original binary image def microstructure (l=256):  n = 5  x, y = np.ogrid[0:l, 0:l] #生成网络  mask = Np.zeros ((l, L))  generator = Np.ra Ndom. Randomstate (1) #随机数种子  points = L * Generator.rand (2, n**2)  mask[(Points[0]). Astype (Np.int), (Points[1]). Astype (np.int)] = 1  mask = ndi.gaussian_filter (Mask, sigma=l/(4.*n)) #高斯滤波  return mask > Mask.mean () data = Mic Rostructure (l=128) #生成测试图片dst =morphology.remove_small_objects (Data,min_size=300,connectivity=1) FIG, (ax1, ax2) = Plt.subplots (1, 2, figsize= (8, 4)) Ax1.imshow (data, Plt.cm.gray, interpolation= ' nearest ') Ax2.imshow (Dst,plt.cm.gray, interpolation= ' nearest ') Fig.tight_layout () plt.show ()

In this example, we delete a small area of less than 300 (from 1 to 0), and the results are as follows:

4, integrated Example: threshold segmentation + closed operation + Connected area Tag + DELETE Cell block + color separation display

Import NumPy as Npimport Matplotlib.pyplot as Pltimport matplotlib.patches as Mpatchesfrom skimage import data,filter,segm entation,measure,morphology,color# load and crop the coin image image = Data.coins () [50:-50, 50:-50]thresh =filter.threshold_otsu (image ) #阈值分割bw =morphology.closing (Image > Thresh, Morphology.square (3)) #闭运算cleared = Bw.copy () #复制segmentation. Clear_ Border (cleared) #清除与边界相连的目标物label_image =measure.label (cleared) #连通区域标记borders = Np.logical_xor (BW, cleared) #异或label _image[borders] = -1image_label_overlay =color.label2rgb (label_image, Image=image) #不同标记用不同颜色显示fig, (ax0,ax1) = Plt.subplots (Figsize= (8, 6)) Ax0.imshow (Cleared,plt.cm.gray) ax1.imshow (Image_label_overlay) for Measure.regionprops (label_image): #循环得到每一个连通区域属性集 #忽略小区域 if Region.area < 100:continue #绘制外包矩形 Minr, Minc, MA XR, maxc = region.bbox rect = mpatches. Rectangle ((Minc, Minr), Maxc-minc, Maxr-minr, Fill=false, edgecolor= ' Red ', linewidth=2) Ax1.add_patch (r ECT) fig.tight_layout () Plt.sHow () 


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.