1,顶帽
2,黑帽
3,形态学梯度
4,源代码示例
import cv2 as cv
import numpy as np
def hat_gray_demo(image): #基于灰度图像的顶帽操作
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
kernel = cv.getStructuringElement(cv.MORPH_RECT, (15, 15))
dst = cv.morphologyEx(gray, cv.MORPH_TOPHAT, kernel)
cimage = np.array(gray.shape, np.uint8)
cimage = 120;
dst = cv.add(dst, cimage)
cv.imshow("tophat_gray", dst)
def hat_binary_demo(image):#基于二值图像的黑帽帽操作
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
kernel = cv.getStructuringElement(cv.MORPH_RECT, (15, 15))
dst = cv.morphologyEx(binary, cv.MORPH_BLACKHAT, kernel)
cv.imshow("blackhat_binary", dst)
def gradient_demo(image): #基本梯度
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))
dst = cv.morphologyEx(binary, cv.MORPH_GRADIENT, kernel)
cv.imshow("gradient", dst)
def gradient2_demo(image):
kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))
dm = cv.dilate(image, kernel)
em = cv.erode(image, kernel)
dst1 = cv.subtract(image, em) # internal gradient
dst2 = cv.subtract(dm, image) # external gradient
cv.imshow("internal", dst1)
cv.imshow("external", dst2)
src = cv.imread("F:/images/lena.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
hat_gray_demo(src)
hat_binary_demo(src)
gradient_demo(src)
gradient2_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()