前言
灰度形态学算法中介绍了灰度形态学算法的相关原理,本篇文章将会利用python
结合numpy
和opencv
实现灰度形态学的一些基本算法,包括,膨胀,腐蚀,开运算,闭运算以及OBR算法和CBR算法。
如下图所示,是一个3×3的Structure Element的基本结构,本次实践中,以中心点坐标[2,2]作为SE的坐标原点。
实现灰度形态学算法之前,首先,需要将原始图像转换为灰度图像,,如下代码所示:
import cv2
import numpy as np
img = cv2.imread("./1582516629222.jpg")
cv2.imshow("original image",img)
cv2.waitKey(0)
img_gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
cv2.imshow("Gray image",img_gray)
cv2.waitKey(0)
灰度膨胀和腐蚀算法的实现
实现灰度膨胀的代码和结果如下所示:
def GrayDialtion(img,SE):
w,h = img.shape
s_w,s_h = SE.shape
img_d = np.zeros((w,h))
img_d = img.copy()
pos_i,pos_j = int(s_w/2),int(s_h/2)
for i in range(pos_i,w-pos_i):
for j in range(pos_j,h-pos_j):
img_d[i,j] = int(np.max(img[i-pos_i:i+pos_i+1,j-pos_j:j+pos_j+1]))
return img_d
SE = np.ones([3,3])
img_dial = GrayDialtion(img_gray,SE)
cv2.imshow("Dial image",img_dial)
cv2.waitKey(0)
灰度腐蚀的相关代码和效果如下所示:
def GrayErosion(img,SE):
w,h = img.shape
s_w,s_h = SE.shape
img_d = np.zeros((w,h))
img_d = img.copy()
pos_i,pos_j = int(s_w/2),int(s_h/2)
for i in range(pos_i,w-pos_i):
for j in range(pos_j,h-pos_j):
img_d[i,j] = int(np.min(img[i-pos_i:i+pos_i+1,j-pos_j:j+pos_j+1]))
return img_d
img_erosion = GrayErosion(img_gray,SE)
cv2.imshow("Gray image",img_erosion)
cv2.waitKey(0)
灰度开运算和闭运算的实现
与二值形态学一样,灰度开运算和闭运算的也是通过灰度膨胀和腐蚀运算的组合而来,灰度开运算代码和效果如下图所示:
def GrayOpen(img,SE):
img_e = GrayErosion(img,SE)
img_o = GrayDialtion(img_e,SE)
return img_o
img_o = GrayOpen(img_gray,SE)
cv2.imshow("open image",img_o)
cv2.waitKey(0)
灰度闭运算的代码和实现效果,如下所示:
def GrayClose(img,SE):
img_d = GrayDialtion(img,SE)
img_c = GrayErosion(img_d,SE)
return img_c
img_c = GrayClose(img_gray,SE)
cv2.imshow("Closing Image",img_c)
cv2.waitKey(0)
OBR和CBR算法的实现
利用灰度形态学算法的组合,可以实现OBR和CBR算法,如下代码所示:
def OBRorCBR(img,SE,mode="OBR"):
(w,h) = img.shape
img_R = np.empty([w,h])
img_copy = img.copy()
if mode=="OBR":
img_O = cv2.morphologyEx(img,cv2.MORPH_OPEN,SE)
elif mode=="CBR":
img_O = cv2.morphologyEx(img,cv2.MORPH_CLOSE,SE)
while(True):
img_O = GrayDialtion(img_O,SE)
for i in range(w):
for j in range(h):
if(img_O[i,j]>img[i,j]):
img_copy[i,j] = img_O[i,j]
if(img_copy==img_O).any():
break
return img_copy
网友评论