本节为《OpenCV计算机视觉实战(Python)》版第四讲,图像形态学处理,的总结。
img = cv2.imread('dige.png')
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
kernel = np.ones((5,5), np.unit8)
erosion = cv2.erode(pie, kernel, iter=1)
cv2.imshow('img_erode', erosion)
cv2.waitKey(0)
cv2.destroyAllWindow()
- 腐蚀操作去除毛刺
- 腐蚀操作中的参数:kernel 表示卷积核,iter表示腐蚀操作的次数。
- 腐蚀的结果,与,迭代次数,核大小有关系。腐蚀次数增大,图像线条会变细。
img = cv2.imread('dige.png')
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
kernel = np.ones((5,5), np.uint8)
dilate = cv2.dilate(img, kernel, iter=1)
cv2.imshow('dilate', dilate)
cv2.waitKey(0)
cv2.destroyAllWindows()
- 与腐蚀操作互为逆运算
- 参数的定义与腐蚀操作一致
img = cv2.imread('dige.png')
cv2.imshow('img', img)
cv2.waitKey()
cv2.destroyAllWindows()
kernel = np.ones((5,5), np.unit8)
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
cv2.imshow('opening', opening)
cv2.waitKey()
cv2.destroyAllWindows()
- 先腐蚀,再膨胀
- 能够有效去除毛刺
img = cv2.imread('dige.png')
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
cv2.imshow('closing', closing)
cv2.waitKey(0)
cv2.destroyAllWindows()
- 先膨胀,再腐蚀
- 无法去除毛刺,只是扩大了边缘
# 梯度 = 膨胀 - 腐蚀
pie = cv2.imread('pie.png')
kernel = np.ones((7,7),np.unit8)
dilate = cv2.dilate(pie,kernel, iter=5)
erosion = cv2.erode(pie,kernel, iter=5)
res = np.hstack((dilate, erosion))
cv2.imshow('res', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 梯度
gradient = cv2.morphologyEx(pie, cv2.MORPH_GRADIENT, kernel)
cv2.imshow('gradient', gradient)
cv2.waitKey(0)
cv2.destroyAllWindows()
- 梯度 = 膨胀 - 腐蚀
- 梯度运算可以得到轮廓
img = cv2.imread('dige.png')
# 礼帽
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
# 黑帽
blackhat = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel)