Advanced morphological processing of python digital image processing

不言
Release: 2018-04-27 10:10:39
Original
4268 people have browsed it

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)
Copy after login

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(&#39;original image&#39;)

ax1.imshow(chull,plt.cm.gray)
ax1.set_title(&#39;convex_hull image&#39;)
Copy after login

##convex_hull_image( ) considers all targets in the picture as a whole, so only one minimum convex polygon is calculated. If there are multiple target objects in the picture and 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 )

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(&#39;many objects&#39;)
ax1.imshow(chull,plt.cm.gray)
ax1.set_title(&#39;convex_hull image&#39;)
plt.show()
Copy after login

##2. Connected area mark

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)
Copy after login

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(&#39;regions number:&#39;,labels.max()+1) #显示连通区域块数(从0开始标记)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))
ax1.imshow(data, plt.cm.gray, interpolation=&#39;nearest&#39;)
ax1.axis(&#39;off&#39;)
ax2.imshow(dst,interpolation=&#39;nearest&#39;)
ax2.axis(&#39;off&#39;)

fig.tight_layout()
plt.show()
Copy after login

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)
Copy after login

Returns the attribute list of all connected blocks. The commonly used attribute list is as follows:


Attribute namearea##bboxtupleBoundary bounding box (min_row, min_col, max_row, max_col)centroidarray Centroid coordinatesconvex_areaintTotal number of pixels in the convex hullconvex_imagendarrayConvex hull with the same size as the bounding boxcoordsndarrayCoordinates of pixels in the areaEccentricity floatEccentricityequivalent_diameter floatThe diameter of a circle with the same area as the areaeuler_number int  Regional Euler numberextent floatRegional area and bounding box area Ratiofilled_areaintThe total number of pixels filled between the area and the bounding boxperimeter floatRegion perimeterlabelintRegion label

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=&#39;nearest&#39;)
ax2.imshow(dst,plt.cm.gray,interpolation=&#39;nearest&#39;)

fig.tight_layout()
plt.show()
Copy after login

在此例中,我们将面积小于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=&#39;red&#39;, linewidth=2)
  ax1.add_patch(rect)
fig.tight_layout()
plt.show()
Copy after login


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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
TypeDescription
int Total number of pixels in the area