This article mainly introduces advanced morphological processing of python digital image processing. Now I will share it with you and give you a reference. Let’s take a look together
Morphological processing, in addition to the most basic expansion, erosion, opening/closing operations, black/white hat processing, there are also some more advanced applications, such as convex hulls and connected region markers , delete small areas, etc.
1. Convex Hull
The convex hull refers to a convex polygon that contains all the white pixels in the image.
The function is:
skimage.morphology.convex_hull_image(image)
The input is a binary image and the output is a logical binary image. The points within the convex hull are True, otherwise they are False
Example:
import matplotlib.pyplot as plt from skimage import data,color,morphology #生成二值测试图像 img=color.rgb2gray(data.horse()) img=(img<0.5)*1 chull = 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')
skimage.morphology.convex_hull_object(image,neighbors=8)
The input parameter image is a binary image, and neighbors indicates whether to use 4-connected or 8-connected. The default is 8-connected. Example:import matplotlib.pyplot as plt from skimage import data,color,morphology,feature #生成二值测试图像 img=color.rgb2gray(data.coins()) #检测canny边缘,得到二值图片 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()
In a binary image, if two pixels are adjacent and have the same value (both 0 or 1), then the two pixels are considered to be in a connected area. All pixels in the same connected area are marked with the same value. This process is called connected area marking. When judging whether two pixels are adjacent, we usually use 4-connected or 8-connected judgment. In an image, the smallest unit is a pixel, and each pixel is surrounded by 8 adjacent pixels. There are two common adjacency relationships: 4-adjacency and 8-adjacency. 4 is adjacent to a total of 4 points, namely up, down, left and right, as shown in the left picture below. 8 There are 8 adjacent points in total, including points at diagonal positions, as shown in the right figure below.
In the skimage package, we use the label() function under the measure submodule to implement connected area labeling.
Function format:
skimage.measure.label(image,connectivity=None)
The image in the parameter represents the binary image that needs to be processed, connectivity represents the connection mode, 1 represents 4 adjacencies , 2 represents 8 adjacencies.
Output an array of labels (labels), starting from 0.
import numpy as np import scipy.ndimage as ndi from skimage import measure,color import matplotlib.pyplot as plt #编写一个函数来生成原始二值图像 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 = microstructure(l=128)*1 #生成测试图片 labels=measure.label(data,connectivity=2) #8连通区域标记 dst=color.label2rgb(labels) #根据不同的标记显示不同的颜色 print('regions number:',labels.max()+1) #显示连通区域块数(从0开始标记) 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 the code, by multiplying by 1 in some places, the bool array can be quickly converted to an int array.
The result is as shown in the figure: there are 10 connected areas, marked 0-9
If you want to operate on each connected area separately, such as calculating Area, circumscribed rectangle, convex hull area, etc., you need to call the regionprops() function of the measure submodule. The format of this function is:
skimage.measure.regionprops(label_image)
Returns the attribute list of all connected blocks. The commonly used attribute list is as follows:
3、删除小块区域
有些时候,我们只需要一些大块区域,那些零散的、小块的区域,我们就需要删除掉,则可以使用morphology子模块的remove_small_objects()函数。
函数格式:skimage.morphology.remove_small_objects(ar,min_size=64,connectivity=1,in_place=False)
参数:
ar: 待操作的bool型数组。
min_size: 最小连通区域尺寸,小于该尺寸的都将被删除。默认为64.
connectivity: 邻接模式,1表示4邻接,2表示8邻接
in_place: bool型值,如果为True,表示直接在输入图像中删除小块区域,否则进行复制后再删除。默认为False.
返回删除了小块区域的二值图像。
import numpy as np import scipy.ndimage as ndi from skimage import morphology import matplotlib.pyplot as plt #编写一个函数来生成原始二值图像 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 = microstructure(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()
在此例中,我们将面积小于300的小块区域删除(由1变为0),结果如下图:
4、综合示例:阈值分割+闭运算+连通区域标记+删除小区块+分色显示
import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches from skimage import data,filter,segmentation,measure,morphology,color #加载并裁剪硬币图片 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] = -1 image_label_overlay =color.label2rgb(label_image, image=image) #不同标记用不同颜色显示 fig,(ax0,ax1)= plt.subplots(1,2, figsize=(8, 6)) ax0.imshow(cleared,plt.cm.gray) ax1.imshow(image_label_overlay) for region in measure.regionprops(label_image): #循环得到每一个连通区域属性集 #忽略小区域 if region.area < 100: continue #绘制外包矩形 minr, minc, maxr, maxc = region.bbox rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr, fill=False, edgecolor='red', linewidth=2) ax1.add_patch(rect) fig.tight_layout() plt.show()
The above is the detailed content of Advanced morphological processing of python digital image processing. For more information, please follow other related articles on the PHP Chinese website!
Type | Description | |
int | Total number of pixels in the area | ##bbox |
Boundary bounding box (min_row, min_col, max_row, max_col) | centroid | |
Centroid coordinates | convex_area | |
Total number of pixels in the convex hull | convex_image | |
Convex hull with the same size as the bounding box | coords | |
Coordinates of pixels in the area | Eccentricity | |
Eccentricity | equivalent_diameter | |
The diameter of a circle with the same area as the area | euler_number | |
Regional Euler number | extent | |
Regional area and bounding box area Ratio | filled_area | |
The total number of pixels filled between the area and the bounding box | perimeter | |
Region perimeter | label | |
Region label |