膨胀腐蚀操作opencv dilate膨胀白膨胀,erode腐蚀是黑吃白。主要针对二值图

效果:
膨胀腐蚀操作opencv dilate膨胀白膨胀,erode腐蚀是黑吃白。主要针对二值图_第1张图片

代码:

import cv2
import numpy as np
from matplotlib import pyplot as plt

if __name__ == "__main__":
    h = 10
    w = 10
    data = np.random.normal(0, 1, [h, w]) # sigma, 2*sigma, 3*sigma之间的数的比例分别为0.68, 0.96, 0.99
    mask_new = data > 2
    print(data)
    print(np.sum(abs(data) < 1) / (h*w))
    print(np.sum(data < 0) / (h * w))
    mask_new = (mask_new * 255).astype(np.uint8)
    mask_new[3:6, 4:6] = 255


    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    a = cv2.dilate(mask_new, kernel) # 膨胀
    b = cv2.erode(a, kernel) #腐蚀


    closing = cv2.morphologyEx(mask_new, cv2.MORPH_CLOSE, kernel) # 先膨胀后腐蚀
    opening = cv2.morphologyEx(mask_new, cv2.MORPH_OPEN, kernel)  # 先腐蚀后膨胀

    plt.figure()
    plt.subplot(231)
    plt.imshow(mask_new, cmap='gray')
    plt.subplot(232)
    plt.imshow(a, cmap='gray')
    plt.subplot(233)
    plt.imshow(b, cmap='gray')

    plt.subplot(234)
    plt.imshow(opening, cmap='gray')
    plt.subplot(235)
    plt.imshow(closing, cmap='gray')
    plt.show()

你可能感兴趣的:(opencv,人工智能,计算机视觉)