顶帽(Top Hat):
原图像与开操作之间的差值图像,突出原图像中比周围亮的区域
黑帽(Black Hat):
闭操作图像与原图像的差值图像, 突出原图像中比周围暗的区域
形态学梯度(Gradient):
基础梯度:基础梯度是用膨胀后的图像减去腐蚀后的图像得到差值图像,称为梯度图像也是opencv中支持的计算形态学梯度的方法,而此方法得到梯度有称为基本梯度。
内部梯度:是用原图像减去腐蚀之后的图像得到差值图像,称为图像的内部梯度。
外部梯度:图像膨胀之后再减去原来的图像得到的差值图像,称为图像的外部梯度。
顶帽python实现以及结果
def top_hat_demo(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) dst = cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, kernel) # 提升亮度 cimage = np.array(gray.shape, np.uint8) cimage = 100 dst = cv2.add(dst, cimage) cv2.imshow("top_hat_demo", dst)
黑帽python实现以及结果
def black_hat_demo(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) dst = cv2.morphologyEx(gray, cv2.MORPH_BLACKHAT, kernel) # 提升亮度 cimage = np.array(gray.shape, np.uint8) cimage = 100 dst = cv2.add(dst, cimage) cv2.imshow("black_hat_demo", dst)
二值图像的顶帽与黑帽操作
def threshold_top_hat_demo(image): # 二值图像顶帽操作 gray = cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY) ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) dst = cv2.morphologyEx(thresh, cv2.MORPH_TOPHAT, kernel) cv2.imshow("dst", dst) def threshold_black_hat_demo(image): # 二值图像黑帽操作 gray = cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY) ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) dst = cv2.morphologyEx(thresh, cv2.MORPH_BLACKHAT, kernel) cv2.imshow("dst", dst)
形态学梯度操作
def gradient1_demo(image): cv2.imshow("image", image) gray = cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY) ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) dst = cv2.morphologyEx(thresh, cv2.MORPH_GRADIENT, kernel) # 基本梯度 cv2.imshow("dst", dst) def gradients2_demo(image): cv2.imshow("image", image) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) dm = cv2.dilate(image, kernel) em = cv2.erode(image, kernel) dst1 = cv2.subtract(image, em) # 内部梯度 dst2 = cv2.subtract(dm, image) # 外部梯度 cv2.imshow("internal", dst1) cv2.imshow("external", dst2)
内部梯度,外部梯度结果