基于python的opencv项目实战笔记(三)—— 图像形态学处理

import cv2 as cv
import matplotlib.pyplot as plt
import numpy as np
def cv_show(name,img):
    cv.imshow(name,img)
    cv.waitKey(0)
    cv.destroyAllWindows()
def cv_erode(img):
    kernel=np.ones((5,5),np.uint8)
    #iterations为迭代次数
    erode1 = cv.erode(img, kernel, iterations=1)
    erode2 = cv.erode(img, kernel ,iterations=2)
    erode3 = cv.erode(img, kernel, iterations=5)
    res=np.hstack((erode2,erode3))
    cv_show('res',res)
def cv_dilate(img):
    kernel = np.ones((5, 5), np.uint8)
    img1 = cv.erode(img, kernel, iterations=2)
    dilate = cv.dilate(img1, kernel, iterations=1)
    res=np.hstack((img1,dilate))
    cv_show('res',res)
#开运算:先腐蚀,后膨胀
def cv_opening(img):
    kernel = np.ones((5, 5), np.uint8)
    opening=cv.morphologyEx(img,cv.MORPH_OPEN,kernel,iterations=2)
    cv_show('opening', opening)
#闭运算:先膨胀,再腐蚀
def cv_closing(img):
    kernel = np.ones((5, 5), np.uint8)
    closing = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel, iterations=5)
    cv_show('closing', closing)
#梯度运算=膨胀-腐蚀(得到边界信息)
def cv_gradient(img):
    kernel = np.ones((5, 5), np.uint8)
    gradient=cv.morphologyEx(img,cv.MORPH_GRADIENT,kernel)
    cv_show('gradient',gradient)
#礼帽=原始输入-开运算结果
def cv_tophat(img):
    kernel = np.ones((5, 5), np.uint8)
    tophat = cv.morphologyEx(img, cv.MORPH_TOPHAT, kernel)
    cv_show('tophat', tophat)
#黑帽=闭运算结果-原始输入
def cv_blackhat(img):
    kernel = np.ones((5, 5), np.uint8)
    blackhat = cv.morphologyEx(img, cv.MORPH_BLACKHAT, kernel)
    cv_show('blackhat', blackhat)
img = cv.imread("D://g.png")
img0 = cv.imread("D://i.png")
#cv_show('img',img)
#cv_show('img0',img0)
#cv_erode(img)#腐蚀
#cv_dilate(img)#膨胀
#cv_opening(img)
#cv_closing(img0)
#cv_gradient(img)
#cv_tophat(img)
cv_blackhat(img)

你可能感兴趣的:(opencv项目实战,opencv,python,计算机视觉)