# OpenCV系列之形态学转换 | 十七

1. 侵蚀

``````
import cv2 as cv
import numpy as np
kernel = np.ones((5,5),np.uint8)
erosion = cv.erode(img,kernel,iterations = 1)``````

2. 扩张

``````
dilation = cv.dilate(img,kernel,iterations = 1) ``````

3. 开运算

``````
opening = cv.morphologyEx(img, cv.MORPH_OPEN, kernel)
``````

4. 闭运算

``````
closing = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel) ``````

5. 形态学梯度

``````

6. 顶帽

``````
tophat = cv.morphologyEx(img, cv.MORPH_TOPHAT, kernel)
``````

7. 黑帽

``````blackhat = cv.morphologyEx(img, cv.MORPH_BLACKHAT, kernel)
``````

``````# 矩形内核
>>> cv.getStructuringElement(cv.MORPH_RECT,(5,5))
array([[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]], dtype=uint8)
# 椭圆内核
>>> cv.getStructuringElement(cv.MORPH_ELLIPSE,(5,5))
array([[0, 0, 1, 0, 0],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[0, 0, 1, 0, 0]], dtype=uint8)
# 十字内核
>>> cv.getStructuringElement(cv.MORPH_CROSS,(5,5))
array([[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[1, 1, 1, 1, 1],
[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0]], dtype=uint8)``````

1.Morphological Operations：http://homepages.inf.ed.ac.uk/rbf/HIPR2/morops.htm at HIPR2