先腐蝕後膨脹的操作稱為開運算
The role of open operation:消除細小物體、在窄區域分離物體、平滑大物體邊界等.
Open operation function: cv2.morphologyEx(圖像, cv2.MORPH_OPEN,矩陣)
示例代碼:
import cv2
import numpy as np
img = cv2.imread("./k.jpg")
k = np.ones((20, 20), np.uint8)
k_img = cv2.morphologyEx(img, cv2.MORPH_OPEN,k)
cv2.imshow("img", img)
cv2.imshow("k_img", k_img)
cv2.waitKey()
運行結果:
原圖
After opening operation:
先膨脹後腐蝕的操作稱為閉運算
作用:填充物體空洞、消除噪聲、連接鄰近物體、平滑邊界等.
closed operation function: cv2.morphologyEx(圖像, cv2.MORPH_CLOSE,矩陣)
import cv2
import numpy as np
img = cv2.imread("./csdnb.jpg")
k1 = np.ones((8, 8), np.uint8)
k2 = np.ones((15, 15), np.uint8)
k3 = np.ones((22, 22), np.uint8)
k1_img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, k1)
k2_img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, k2)
k3_img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, k3)
cv2.imshow("img", img)
cv2.imshow("k1_img", k1_img)
cv2.imshow("k2_img", k2_img)
cv2.imshow("k3_img", k3_img)
cv2.waitKey()
運行結果:
原圖
k1:
k2:
k3: