


Advanced morphological processing of python digital image processing
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:
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 |
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!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Notepad++7.3.1
Easy-to-use and free code editor