题目地址:gzr2017/ImageProcessing100Wen
# 第47题 膨胀
# 对经过大津二值化处理后的图像进行膨胀处理
def dilate(image):
H, W = image.shape
k = ([0, 1, 0],
[1, 0, 1],
[0, 1, 0])
result = np.zeros((H+2,W+2)).astype(np.uint8)
result[1:H+1, 1:W+1] = image
mid = result.copy()
for h in range(1, H+1):
for w in range(1, W+1):
near_max = np.max(k * mid[h-1:h+2, w-1:w+2])
if near_max == 255:
result[h, w] = 255
result = result[1:H+1, 1:W+1].astype(np.uint8)
return result
# 第48题 膨胀
# 对经过大津二值化处理后的图像进行膨胀处理
def erode(image):
H, W = image.shape
k = ([0, 1, 0],
[1, 0, 1],
[0, 1, 0])
result = np.zeros((H+2,W+2)).astype(np.uint8)
result[1:H+1, 1:W+1] = image
mid = result.copy()
for h in range(1, H+1):
for w in range(1, W+1):
near_sum = np.sum(k * mid[h-1:h+2, w-1:w+2])
if near_sum < 255*4:
result[h, w] = 0
result = result[1:H+1, 1:W+1].astype(np.uint8)
return result
今天完成了第47与第48题,学习了用python实现腐蚀与膨胀操作的方法,稍微提醒一下,腐蚀与膨胀都是针对白色连通域而言的,而非黑色连通域
如有任何问题或错误,欢迎在评论区讨论和指正