import cv2
import numpy as np
from matplotlib import pyplot as plt
形态学运算的基础是腐蚀和膨胀
腐蚀运算通过降低边缘噪点实现平滑,膨胀通过扩大边缘实现消除内部噪点
o = cv2.imread("erode_hand.jpg") #原图为黑底白色mask
kernel = np.ones((6, 6), np.uint8) #定义6*6的算子
erd = cv2.erode(o, kernel, iterations=2) #此处定义迭代运算2次
dil = cv2.dilate(o, kernel, iterations=2)
plt.figure("original - erode - dilate")
#调用plot中的imshow函数来显示多图对比
plt.subplot(131), plt.imshow(o, cmap=plt.cm.gray), plt.axis("off")
#cmap为色彩空间,原图为灰度图,故cmap=plt.cm.gray
plt.subplot(132), plt.imshow(erd, cmap=plt.cm.gray), plt.axis("off")
plt.subplot(133), plt.imshow(dil, cmap=plt.cm.gray), plt.axis("off")
plt.show() #显示图像

通用形态学运算
dst = cv2.morphologyEX(scr, op, kernel[, anchor[, iterations[, borderType[, borderValye]]]]])
op====> cv2.MORPH_OPEN 开运算
首先腐蚀然后膨胀,达到外部去噪目的
open = cv2.morphologyEx(o, cv2.MORPH_OPEN, kernel, iterations=2)
plt.figure("original - open")
plt.subplot(121), plt.imshow(o, cmap=plt.cm.gray), plt.axis("off")
plt.subplot(122), plt.imshow(open, cmap=plt.cm.gray), plt.axis("off")
plt.show()

op====> cv2.MORPH_CLOSE 闭运算
首先膨胀然后腐蚀,达到内部去噪目的
close = cv2.morphologyEx(o, cv2.MORPH_CLOSE, kernel, iterations=2)
plt.figure("original - close")
plt.subplot(121), plt.imshow(o, cmap=plt.cm.gray), plt.axis("off")
plt.subplot(122), plt.imshow(close, cmap=plt.cm.gray), plt.axis("off")
plt.show()

op====> cv2.MORPH_TOPHAT 礼帽运算
原始图像减去开运算图像,通常得到比原图更亮的边缘噪点图像
tophat = cv2.morphologyEx(o, cv2.MORPH_TOPHAT, kernel)
plt.figure("original - open - tophat")
plt.subplot(131), plt.imshow(o, cmap=plt.cm.gray), plt.axis("off")
plt.subplot(132), plt.imshow(open, cmap=plt.cm.gray), plt.axis("off")
plt.subplot(133), plt.imshow(tophat, cmap=plt.cm.gray), plt.axis("off")
plt.show()

op====> cv2.MORPH_BLACKHAT 黑帽运算
闭运算减去原始图像,得到原始图像中的小孔,通常得到比原图暗的噪点图像
blackhat = cv2.morphologyEx(o, cv2.MORPH_BLACKHAT, kernel)
plt.figure("original - close - blackhat")
plt.subplot(131), plt.imshow(o, cmap=plt.cm.gray), plt.axis("off")
plt.subplot(132), plt.imshow(close, cmap=plt.cm.gray), plt.axis("off")
plt.subplot(133), plt.imshow(blackhat, cmap=plt.cm.gray), plt.axis("off")
plt.show()

网友评论