# OpenCV 中的圖像處理 005_形態變換

## 理論

### 1. 侵蝕

``````import cv2 as cv
import numpy as np

def erosion():
kernel = np.ones((5, 5), np.uint8)
erosion = cv.erode(img, kezhangsanrnel, iterations=1)

edge = np.full((img.shape[0], 3, 1), 255, np.uint8);

images = [img, edge, erosion]
dest = cv.hconcat(images)

cv.imshow("Image", dest)
cv.waitKey(-1)

if __name__ == "__main__":
erosion()
``````

### 2. 膨脹

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

### 3. 開

``````def opening():

for i in range(50):
row = random.randint(0, img.shape[0] - 1)
col = random.randint(0, img.shape[1] - 1)
img[row][col] = 255

kernel = np.ones((5, 5), np.uint8)
opening = cv.morphologyEx(img, cv.MORPH_OPEN, kernel)

edge = np.full((img.shape[0], 3, 1), 255, np.uint8);

images = [img, edge, opening]
dest = cv.hconcat(images)

cv.imshow("Image", dest)
cv.waitKey(-1)
``````

### 4. 閉

``````def closing():

for i in range(5000):
row = random.randint(0, img.shape[0] - 1)
col = random.randint(0, img.shape[1] - 1)
img[row][col] = 0

kernel = np.ones((5, 5), np.uint8)
closing = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel)

edge = np.full((img.shape[0], 3, 1), 255, np.uint8);

images = [img, edge, closing]
dest = cv.hconcat(images)

cv.imshow("Image", dest)
cv.waitKey(-1)

if __name__ == "__main__":
closing()
``````

### 5. 形態梯度

``````    gradient = cv.morphologyEx(img, cv.MORPH_GRADIENT, kernel)
``````

### 6. 禮帽

``````def top_hat():

kernel = np.ones((9, 9), np.uint8)
tophat = cv.morphologyEx(img, cv.MORPH_TOPHAT, kernel)

edge = np.full((img.shape[0], 3, 1), 255, np.uint8);

images = [img, edge, tophat]
dest = cv.hconcat(images)

cv.imshow("Image", dest)
cv.waitKey(-1)
``````

### 7. 黑帽

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

## 結構元素

``````# Rectangular 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)
# Elliptical Kernel
>>> 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)
# Cross-shaped Kernel
>>> 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. HIPR2 的 Morphological Operations

## 練習

Morphological Transformations

Done.