OpenCV+python:顶帽、黑帽、形态学梯度

1,顶帽
OpenCV+python:顶帽、黑帽、形态学梯度_第1张图片2,黑帽
OpenCV+python:顶帽、黑帽、形态学梯度_第2张图片
3,形态学梯度
OpenCV+python:顶帽、黑帽、形态学梯度_第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()

OpenCV+python:顶帽、黑帽、形态学梯度_第4张图片OpenCV+python:顶帽、黑帽、形态学梯度_第5张图片OpenCV+python:顶帽、黑帽、形态学梯度_第6张图片OpenCV+python:顶帽、黑帽、形态学梯度_第7张图片OpenCV+python:顶帽、黑帽、形态学梯度_第8张图片OpenCV+python:顶帽、黑帽、形态学梯度_第9张图片

你可能感兴趣的:(OpenCV/基本图像处理算法)