(针对二值图像)
import cv2 #opencv读取的格式是BGR
import matplotlib.pyplot as plt
import numpy as np #基本数据计算工具包
%matplotlib inline #专有魔法指令,即时显示
kernel = np.ones((3,3), np.uint8)
dige_eosion = cv2.erode(img, kernel, iterations = 1)
cv2.imshow('erosion', erosion)
cv2.waitKey(0)
cv2.destoryAllWindows()
kernel = np.ones((30,3)0, np.uint8)
eosion_1 = cv2.erode(img, kernel, iterations = 1)
eosion_2 = cv2.erode(img, kernel, iterations = 1)
eosion_3 = cv2.erode(img, kernel, iterations = 1)
res = np.hstack((eosion_1, eosion_2, eosion_3))
cv2.imshow('res', res)
cv2.waitKey(0)
cv2.destoryAllWindows()
kernel = np.ones((3,3), np.uint8)
dige_dilate = cv2.dilate(img, kernel, iterations = 1)
cv2.imshow('dilate', dige_dilate)
cv2.waitKey(0)
cv2.destoryAllWindows()
# 开运算:先腐蚀,再膨胀
img = cv2.imread('dige.png')
kernel = np.ones((5,5), np.uint8)
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
cv2.imshow('opening', opening)
cv2.waitKey(0)
cv2.destoryAllWindows()
# 闭运算:先膨胀,再腐蚀
img = cv2.imread('dige.png')
kernel = np.ones((5,5), np.uint8)
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
cv2.imshow('closing ', closing)
cv2.waitKey(0)
cv2.destoryAllWindows()
# 梯度运算=膨胀-腐蚀
pie = cv2.imread('pie.png')
kernel = np.ones((7,7), np.uint8)
dilate = cv2.dilate(pie, kernel, iterations = 5)
erosion = cv2.erode(pie, kernel, iterations = 5)
res = np.hstack((dilate, erosion))
gradient = cv2.morphologyEx(pie, cv2.MORPH_GRADIENT, kernel)
cv2.imshow('res', res)
cv2.imshow('gradient ', gradient )
cv2.waitKey(0)
cv2.destoryAllWindows()
# 礼帽=原始输入-开运算结果
img = cv2.imread('dige.png')
tophat= cv2.morphologyEx(pie, cv2.MORPH_TOPHAT, kernel)
cv2.imshow('tophat', tophat)
cv2.waitKey(0)
cv2.destoryAllWindows()
# 黑帽=闭运算-原始输入
img = cv2.imread('dige.png')
blackhat= cv2.morphologyEx(pie, cv2.MORPH_BLACKHAT, kernel)
cv2.imshow('blackhat', blackhat)
cv2.waitKey(0)
cv2.destoryAllWindows()
numpy.ones(shape, dtype=None, order=‘C’)
函数返回给定形状和数据类型的新数组,其中元素的值设置为1。此函数与numpy zeros()函数非常相似。
形状是一个int或一个int元组,用于定义数组的大小。 如果我们仅指定一个int变量,则将返回一维数组。 对于一个整数元组,将返回给定形状的数组。
dtype是一个可选参数,默认值为float。 它用于指定数组的数据类型,例如int。
该顺序定义是在内存中以行优先(C风格)还是列优先(Fortran风格)顺序存储多维数组。
cv2.erode(img, kernel, iterations)
腐蚀操作
cv2.dilate(img1, kernel, iterations)
膨胀操作
cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
开运算(先腐蚀再膨胀)
cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
闭运算(先膨胀再腐蚀)
cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel)
梯度运算(膨胀-腐蚀)
cv2.morphologyEx(img,cv2.MORPH_TOPHAT,kernel)
顶帽运算(原始值-开运算)
cv2.morphologyEx(img,cv2.MORPH_BLACKHAT,kernel)
底帽运算(闭运算-原始值)