opencv 膨胀腐蚀开闭

阅读更多
# -*-encoding:utf-8-*-
import pytesseract
from PIL import Image
from PIL import ImageFilter
from PIL import ImageFont
from PIL import ImageDraw
import numpy as np
from PIL import Image

import cv2


def main():
    # img = cv2.imread("test001.jpg") #读取图片
    # cv2.imshow("1",img) #显示图片
    # cv2.waitKey(10000)# 延时10s

    # image = Image.open("test002.png")
    # img = image.convert('1')  # 转化为灰度图

    # img.show()

    img = cv2.imread("test002.png", 0)
    kernel = np.ones((3, 3), np.uint8)  # 全为1的过滤数组
    print(kernel)

    # 腐蚀(去白小点)(取最小值)
    img2 = cv2.erode(img, kernel)  # 腐蚀
    cv2.imshow('canny', img2)
    cv2.waitKey(2000)
    # cv2.waitKey()

    # 膨胀(去黑小点)(取最大值)
    img3 = cv2.dilate(img, kernel)  # 膨胀
    cv2.imshow('canny', img3)
    cv2.waitKey(2000)
    # cv2.waitKey()

    # 先腐蚀后膨胀叫开运算(因为先腐蚀会分开物体,这样容易记住),其作用是:分离物体,消除小区域。
    opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)  # 开运算
    cv2.imshow('canny', opening)
    cv2.waitKey(2000)

    # 闭运算则相反:先膨胀后腐蚀(先膨胀会使白色的部分扩张,以至于消除/"闭合"物体里面的小黑洞,所以叫闭运算)
    closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)  # 闭运算
    cv2.imshow('canny', closing)
    cv2.waitKey(2000)


if __name__ == '__main__':
    main()

你可能感兴趣的:(opencv 膨胀腐蚀开闭)