顶帽
顶帽是原图像与开操作之间的差值图像(右图),最后得到的是原图中各个小块的高亮区,即提取出了原图中的高亮斑点。
黑帽
黑帽是闭操作图像与原图像的差值图像,可以提取出原图中的黑色斑点。
形态学梯度
形态学梯度包含:基本梯度、内部梯度、外部梯度
基本梯度是用膨胀后的图像减去腐蚀后的图像得到差值图像,也是opencv中支持的计算形态学梯度的方法,而此方法得到的梯度又被称为基本梯度。
内部梯度是用原图像减去腐蚀之后的图像得到的差值图像,称为图像的内部梯度。
外部梯度图像膨胀之后再减去原来的图像得到的差值图像,称为图像的外部梯度。
视频源码:
import cv2 as cv
import numpy as np
def top_hat_demo(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
# kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5)) # 获取核,形状是 5 x 5 像素的矩形
kernel = cv.getStructuringElement(cv.MORPH_RECT, (15, 15))
dst = cv.morphologyEx(gray, cv.MORPH_TOPHAT, kernel)
dst = cv.add(dst, 100)
cv.imshow("top-hat", dst)
def black_hat_demo(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
# kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5)) # 获取核,形状是 5 x 5 像素的矩形
kernel = cv.getStructuringElement(cv.MORPH_RECT, (15, 15))
dst = cv.morphologyEx(gray, cv.MORPH_BLACKHAT, kernel)
dst = cv.add(dst, 100)
cv.imshow("black-hat", dst)
def top_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, (5, 5)) # 获取核,形状是 5 x 5 像素的矩形
kernel = cv.getStructuringElement(cv.MORPH_RECT, (15, 15))
dst = cv.morphologyEx(binary, cv.MORPH_TOPHAT, kernel)
cv.imshow("top-hat-binary", dst)
def black_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, (5, 5)) # 获取核,形状是 5 x 5 像素的矩形
kernel = cv.getStructuringElement(cv.MORPH_RECT, (15, 15))
dst = cv.morphologyEx(binary, cv.MORPH_BLACKHAT, kernel)
cv.imshow("black-hat-binary", dst)
def morphology_base_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 morphology_gradient_demo(image):
kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))
dm = cv.dilate(image, kernel)
em = cv.erode(image, kernel)
internal_gradient = cv.subtract(image, em)
external_gradient = cv.subtract(dm, image)
cv.imshow("internal gradient", internal_gradient)
cv.imshow("external gradient", external_gradient)
print("-----------Python OpenCV Tutorial--------------")
src = cv.imread("C:/cv-samples/data/lena.jpg")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
top_hat_demo(src)
black_hat_demo(src)
top_hat_binary_demo(src)
black_hat_binary_demo(src)
morphology_base_gradient_demo(src)
morphology_gradient_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()