图像的基本运算——形态学处理
注意:形态学所有操作针对二值图像!!!
1. 腐蚀操作(erode)
示例:
import cv2
import numpy as np
o = cv2.imread("image",cv2.IMREAD_UNCHANGED)
k = np.ones((5,5),np.uint8)
r = cv2.erode(o,k,iterations=2) #第一个参数是原图像,第二个参数是卷积核,第三个参数是迭代次数
cv2.imshow("original",o)
cv2.imshow("result",r)
cv2.waitKey()
cv2.destroyAllWindows()
2. 膨胀操作(dilate)
示例:
import cv2
import numpy as np
o=cv2.imread("image",cv2.IMREAD_UNCHANGED)
k=np.ones((5,5),np.uint8)
r=cv2.dilate(o,k,iterations=1)
cv2.imshow("original",o)
cv2.imshow("result",r)
cv2.waitKey()
cv2.destroyAllWindows()
效果展示:
3. 开运算
开运算(image)=膨胀(腐蚀)
import cv2
import numpy as np
o=cv2.imread("image",cv2.IMREAD_UNCHANGED)
k=np.ones((6,6),np.uint8)
r=cv2.morphologyEx(o,cv2.MORPH_OPEN,k)
cv2.imshow("original",o)
cv2.imshow("result",r)
cv2.waitKey()
cv2.destroyAllWindows()
效果展示
4. 闭运算
闭运算(image)=腐蚀(膨胀)
import cv2
import numpy as np
o=cv2.imread("image",cv2.IMREAD_UNCHANGED)
k=np.ones((5,5),np.uint8)
r=cv2.morphologyEx(o,cv2.MORPH_CLOSE,k)
cv2.imshow("original",o)
cv2.imshow("result",r)
cv2.waitKey()
cv2.destroyAllWindows()
5. 梯度运算 Gradient (可以获取图像轮廓)
import cv2
import numpy as np
o=cv2.imread("image",cv2.IMREAD_UNCHANGED)
k=np.ones((5,5),np.uint8)
r=cv2.morphologyEx(o,cv2.MORPH_GRADIENT,k)
cv2.imshow("original",o)
cv2.imshow("result",r)
cv2.waitKey()
cv2.destroyAllWindows()
6 礼貌运算 Tophat
礼貌(image)= image -开运算(image)
import cv2
import numpy as np
o=cv2.imread("image",cv2.IMREAD_UNCHANGED)
k=np.ones((5,5),np.uint8)
r=cv2.morphologyEx(o,cv2.MORPH_TOPHAT,k)
cv2.imshow("original",o)
cv2.imshow("result",r)
cv2.waitKey()
cv2.destroyAllWindows()
7. 黑帽运算 blackhat
import cv2
import numpy as np
o=cv2.imread("image",cv2.IMREAD_UNCHANGED)
k=np.ones((10,10),np.uint8)
r=cv2.morphologyEx(o,cv2.MORPH_BLACKHAT,k)
cv2.imshow("original",o)
cv2.imshow("result",r)
cv2.waitKey()
cv2.destroyAllWindows()