Opencv4 官方文档 : https://docs.opencv.org/4.2.0/
Opencv4 for Python中文文档点击下载:OpenCV4 for Python 中文文档
cv.morphologyEx(src, op, kernel, dst=None, anchor=None, iterations=None, borderType=None, borderValue=None)
开操作:
demo1:
def open_demo(image):
print(image.shape)
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
cv.imshow("binary", binary)
kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))
dst = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel=kernel)
cv.imshow("open_demo", dst)
def open_line(image):
print(image.shape)
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
cv.imshow("binary", binary)
# kernel = cv.getStructuringElement(cv.MORPH_RECT, (15, 1))#去掉竖线
# kernel = cv.getStructuringElement(cv.MORPH_RECT, (15, 1))#去掉水平线
kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))#去掉背景干扰线
dst = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel=kernel)
cv.imshow("open_line", dst)
def open_line(image):
print(image.shape)
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
cv.imshow("binary", binary)
# kernel = cv.getStructuringElement(cv.MORPH_RECT, (15, 1))#去掉竖线
# kernel = cv.getStructuringElement(cv.MORPH_RECT, (15, 1))#去掉水平线
kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))#去掉背景干扰线
dst = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel=kernel)
cv.imshow("open_line", dst)
def black_hat_demo(image):
gray=cv.cvtColor(image,cv.COLOR_BGR2GRAY)
#构建形态学元素 提高内核矩阵(10,10)可以提取更多元素
kernel=cv.getStructuringElement(cv.MORPH_RECT,(10,10))
#黑帽处理
dst=cv.morphologyEx(gray,cv.MORPH_BLACKHAT,kernel)
#如果图像较黑可以用图像增强看看效果
cimage=np.array(gray.shape,np.uint8)
cimage=50
dst=cv.add(dst,cimage)
cv.imshow('black_hat',dst)
def top_hat_demo(image):
gray=cv.cvtColor(image,cv.COLOR_BGR2GRAY)
#构建形态学元素 提高内核矩阵(10,10)可以提取更多元素
kernel=cv.getStructuringElement(cv.MORPH_RECT,(10,10))
#黑帽处理
dst=cv.morphologyEx(gray,cv.MORPH_TOPHAT,kernel)
#如果图像较黑可以用图像增强看看效果
cimage=np.array(gray.shape,np.uint8)
cimage=50
dst=cv.add(dst,cimage)
cv.imshow('top_hat',dst)
就是膨胀图像减去腐蚀图像的结果,,得到图像的轮廓。分为基本梯度,内、外梯度
demo1:基本梯度
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)
转载请注明转自:https://leejason.blog.csdn.net/article/details/106443742