腐蝕cv2.erode()
dst = cv2.erode(.src,kernel[,anchor[,iterations[.borderType[,borderValue]]]])
- kernel:腐蝕操作時的結構類型。可以自訂亦可透過函數cv2.getStructuringElement()產生
- iterations:腐蝕操作反覆次數,預設為1
- borderType:預設為BORDER_CONSTANT。P8-5
EX
# 8.1使用陣列示範腐蝕的基本原理
import cv2
import numpy as np
img = np.zeros((5,5),np.uint8)
img[1:4,1:4] = 1
kernel = np.ones((3,1),np.uint8)
erosion = cv2.erode(img,kernel)
print('img=\n',img)
print('kernel=\n',kernel)
print('erosion=\n',erosion)
膨脹
cv2.dilate()
cv2.dilate(src,kernel,[anchor[,iterations[,borderType[,borderValue]]]])
EX
#8.4膨脹
import cv2
import numpy as np
img = np.zeros((5,5),np.uint8)
img[2:3,1:4]=1
kernel=np.ones((3,1),np.uint8)
dilation = cv2.dilate(img,kernel)
print('img\n',img)
print('kernel\n',kernel)
print('dilation\n',dilation)
通用型態學函式
cv2.morphologyEx()
cv2.morphologyEx(src,op,kernel[,anchor[,iterations[,borderType[,borderValue]]]]])
先侵蝕後膨脹,用於去躁、計算
opening = cv2.morphologyEx(img,cv2.MORGE_OPEN,kernel)
EX
#8.7 open
import cv2
import numpy as np
img1 = cv2.imread('ren.jpg')
img2 = cv2.imread('ran.jpg')
k = np.ones((10,10),np.uint8)
r1 = cv2.morphologyEx(img1,cv2.MORPH_OPEN,k)
r2 = cv2.morphologyEx(img2,cv2.MORPH_OPEN,k)
cv2.imshow('img1',img1)
cv2.imshow('img2',img2)
cv2.imshow('r1',r1)
cv2.imshow('r2',r2)
cv2.waitKey()
cv2.destroyAllWindows()
閉運算 close
先膨脹後侵蝕,用於關閉物體內部的小孔、去除物體的小黑點、將不同前景影像進行連接
opening = cv2.morphologyEx(img,cv2.MORGE_CLOSE,kernel)
形態學梯度運算
此為用open影像-close影像,可以取得影像的邊緣
cv2.
GRADIENT = cv2.morphologyEx(img,cv2.MORGE_GRADIENT,kernel)
EX
#8.9 形態學梯度運算
import cv2
import numpy as np
img = cv2.imread('ren.jpg')
k = np.ones((5,5),np.uint8)
r = cv2.morphologyEx(img,cv2.MORPH_GRADIENT,k)
cv2.imshow('img',img)
cv2.imshow('r',r)
cv2.waitKey()
cv2.destroyAllWindows()
禮帽運算
用原始影像減去open影像,用於得到影像的雜訊或獲得比原始影像更亮的邊緣資訊
TOPHAT= cv2.morphologyEx(img,cv2.MORGE_TOPHAT,kernel)
EX
#8.10 TOPHAT
import cv2
import numpy as np
img = cv2.imread('ran.jpg')
k = np.ones((5,5),np.uint8)
r = cv2.morphologyEx(img,cv2.MORPH_TOPHAT,k)
cv2.imshow('img',img)
cv2.imshow('r',r)
cv2.waitKey()
cv2.destroyAllWindows()
黑帽運動
為close影像-原始影像,用於取得影像內部小孔,或景色中的小黑點,或得到比原始影像的邊緣更暗的邊緣部分。
BLACKHAT= cv2.morphologyEx(img,cv2.MORGE_BLACKHAT,kernel)
EX
#8.11 BLACKHAT
import cv2
import numpy as np
img = cv2.imread('ran.jpg')
k = np.ones((5,5),np.uint8)
r = cv2.morphologyEx(img,cv2.MORPH_BLACKHAT,k)
cv2.imshow('img',img)
cv2.imshow('r',r)
cv2.waitKey()
cv2.destroyAllWindows()
核函數
公歸的kernel
retual = cv2.getStructuringElement(shape,ksize[,anchor])
shape形狀類型
類型 |
說明 |
cv2.MORPH_RECT |
矩形結構。元素皆為1 |
cv2.MORPH_CROSS |
十字形元素。對角線元素值都是1 |
cv2.MORPH_ELLIPSE |
橢圓形結構元素 |
EX
#8.13 核函數
import cv2
import numpy as np
img = cv2.imread('sun.jpg')
k1 = cv2.getStructuringElement(cv2.MORPH_RECT,(59,59))
k2 = cv2.getStructuringElement(cv2.MORPH_CROSS,(59,59))
k3 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(59,59))
r1 = cv2.dilate(img,k1)
r2 = cv2.dilate(img,k2)
r3 = cv2.dilate(img,k3)
cv2.imshow('r1',r1)
cv2.imshow('r2',r2)
cv2.imshow('r3',r3)
cv2.waitKey()
cv2.destroyAllWindows()