OpenCV:开运算、闭运算、形态学梯度:基础梯度、顶帽、黑帽
import cv2
img = cv2.imread('星空.jpg')
cv2.imshow('原图', img)
# # 转成灰度图片
img_H = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化
ret,img_T =cv2.threshold(img_H, 100, 255, cv2.THRESH_BINARY) #阈值范围100-255
cv2.imshow('二值化原图', img_T)
# k_0 = np.ones((3, 3), np.uint8)
k_1 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5)) #3*3的矩形框,全为1,与13行相同
'''开运算:先腐蚀再膨胀,将近邻目标分离'''
img_K = cv2.morphologyEx(img, cv2.MORPH_OPEN, k_1)
img_KT = cv2.morphologyEx(img_T, cv2.MORPH_OPEN, k_1)
cv2.imshow('开运算', img_K)
cv2.imshow('二值化开运算', img_KT)
'''闭运算;先膨胀再腐蚀,将近邻目标融合'''
img_B = cv2.morphologyEx(img, cv2.MORPH_CLOSE, k_1)
img_BT = cv2.morphologyEx(img_T, cv2.MORPH_CLOSE, k_1)
cv2.imshow('闭运算', img_B)
cv2.imshow('二值化闭运算', img_BT)
'''形态学梯度:基础梯度,膨胀-腐蚀'''
img_X = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, k_1)
img_XT = cv2.morphologyEx(img_T, cv2.MORPH_GRADIENT, k_1)
cv2.imshow('基础梯度', img_X)
cv2.imshow('二值化基础梯度', img_XT)
'''顶帽:原图-开运算'''
img_D = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, k_1)
img_DT = cv2.morphologyEx(img_T, cv2.MORPH_TOPHAT, k_1)
cv2.imshow('顶帽', img_D)
cv2.imshow('二值化顶帽', img_DT)
'''黑帽:闭运算-原图'''
img_H = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, k_1)
img_HT = cv2.morphologyEx(img_T, cv2.MORPH_BLACKHAT, k_1)
cv2.imshow('黑帽', img_H)
cv2.imshow('二值化黑帽', img_HT)
cv2.waitKey(0)
cv2.destroyAllWindows()
https://www.bilibili.com/video/BV16U4y1D7iP/?spm_id_from=333.1007.top_right_bar_window_history.content.click&vd_source=b89ce2a9b55dab86caa0ee60b66c9f86