【千律】OpenCV基础:图像的形态学梯度

环境:Python3.8 和 OpenCV

内容:图像的形态学梯度

形态学梯度:获取轮廓 

import cv2 as cv
import matplotlib.pyplot as plt


# 封装图片显示函数
def image_show(image):
    if image.ndim == 2:
        plt.imshow(image, cmap='gray')
    else:
        image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
        plt.imshow(image)
    plt.show()


if __name__ == '__main__':

    # 读取灰度图像
    img_desk = cv.imread('desk.png', 0)

    # 灰度图二值化
    threshold = 150     # 二值化分割阈值
    max_value = 255     # 图像中的最大值
    [_, img_bin] = cv.threshold(img_desk, threshold, max_value, cv.THRESH_BINARY)

    # 建立结构元
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))

    # 形态学梯度
    img_grad1 = cv.morphologyEx(img_bin, cv.MORPH_GRADIENT, kernel)

    # 显示图像
    image_show(img_grad1)

    # 形态学梯度计算
    img_grad2 = cv.subtract(cv.dilate(img_bin, kernel), cv.erode(img_bin, kernel))

    # 显示图像
    image_show(img_grad2)

你可能感兴趣的:(OpenCV基础,python,opencv)