OpenCV---其他形态学操作

一:顶帽实现(原图像与开操作图像的差值)

import cv2 as cv
import numpy as np

def top_hat_demo(image):
    gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
    ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)
    cv.imshow("binary",binary)  #这里的二值化图像就可以看作是原图像(注意:基于腐蚀膨胀是可以直接对彩色图像操作的))
    kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE,(5,5))
    dst = cv.morphologyEx(binary,cv.MORPH_OPEN,kernel)  #查看开操作图像
    cv.imshow("open_demo",dst)
    dst = cv.morphologyEx(binary,cv.MORPH_TOPHAT,kernel)  #查看顶帽图像
    cv.imshow("top_hat_demo",dst)


src = cv.imread("./cir.png")  #读取图片
cv.namedWindow("input image",cv.WINDOW_AUTOSIZE)    #创建GUI窗口,形式为自适应
cv.imshow("input image",src)    #通过名字将图像和窗口联系

top_hat_demo(src)

cv.waitKey(0)   #等待用户操作,里面等待参数是毫秒,我们填写0,代表是永远,等待用户操作
cv.destroyAllWindows()  #销毁所有窗口

二:黑帽实现(原图像与闭操作图像的差值)

def black_hat_demo(image):
    gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
    ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)
    cv.imshow("binary",binary)
    kernel = cv.getStructuringElement(cv.MORPH_RECT,(15,15))
    dst = cv.morphologyEx(binary,cv.MORPH_CLOSE,kernel)
    cv.imshow("close_demo",dst)
    dst = cv.morphologyEx(binary,cv.MORPH_BLACKHAT,kernel)
    cv.imshow("black_hat_demo",dst)

 三:图像的梯度

(一)基本梯度(膨胀后的图像与腐蚀后的图像差值)

def graditent_demo(image):
    gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
    ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)
    cv.imshow("binary",binary)
    kernel = cv.getStructuringElement(cv.MORPH_RECT,(15,15))
    dst = cv.dilate(binary, kernel)
    cv.imshow("dilate_demo", dst)
    dst = cv.erode(binary, kernel)
    cv.imshow("erode_demo", dst)
    dst = cv.morphologyEx(binary,cv.MORPH_GRADIENT,kernel)
    cv.imshow("graditent_demo",dst)

(二)内部梯度(原图像减去腐蚀后的图像差值)

def graditent_demo(image):
    gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
    ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)
    cv.imshow("binary",binary)
    kernel = cv.getStructuringElement(cv.MORPH_RECT,(15,15))
    erode_dst = cv.erode(binary, kernel)
    cv.imshow("erode_demo", erode_dst)
    dst2 = cv.subtract(dilate_dst,binary)
    cv.imshow("inner graditent",dst1)

(三)外部梯度(膨胀后图像与原图差值)

def graditent_demo(image):
    gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
    ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)
    cv.imshow("binary",binary)
    kernel = cv.getStructuringElement(cv.MORPH_RECT,(15,15))
    dilate_dst = cv.dilate(binary, kernel)
    cv.imshow("dilate_demo", dilate_dst)
    dst2 = cv.subtract(dilate_dst,binary)
    cv.imshow("outer graditent",dst2)

 

posted @ 2018-07-07 17:49  山上有风景  阅读(767)  评论(2编辑  收藏  举报