显示图像
def display(img):
cv2.imshow("img",img)
cv2.waitKey()
cv2.destroyAllWindows()
腐蚀操作
def erode_(img):
kernel = np.ones((5,5),np.uint8)
erodesion = cv2.erode(img,kernel,iterations=1)
display(erodesion)
膨胀操作
def dilate_(img):
kernel = np.ones((3,3),np.uint8)
erodesion = cv2.dilate(img,kernel,iterations=2)
display(erodesion)
开运算,先腐蚀后膨胀
def morphologyEx_open(img):
kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel,iterations=1)
display(opening)
闭运算,先膨胀后腐蚀
def morphologyEx_close(img):
kernel = np.ones((5,5),np.uint8)
closing = cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel,iterations=2)
display(closing)
梯度运算,膨胀-腐蚀(得到边缘)
def gradient_(img):
kernel = np.ones((5,5),np.uint8)
gradient = cv2.morphologyEx(img,cv2.MORPH_GRADIENT,kernel)
display(gradient)
礼帽,原始-开运算
def morphologyEx_top_hat(img):
kernel = np.ones((5,5),np.uint8)
top_hat = cv2.morphologyEx(img,cv2.MORPH_TOPHAT,kernel,iterations=1)
display(top_hat)
黑帽,闭运算-原始
def morphologyEx_black_hat(img):
kernel = np.ones((5,5),np.uint8)
black_hat = cv2.morphologyEx(img,cv2.MORPH_BLACKHAT,kernel,iterations=1)
display(black_hat)
素材
完整代码
# -*- coding:utf-8 -*-
import numpy as np
import cv2
# 显示图像
def display(img):
cv2.imshow("img",img)
cv2.waitKey()
cv2.destroyAllWindows()
# 腐蚀操作
def erode_(img):
kernel = np.ones((5,5),np.uint8)
erodesion = cv2.erode(img,kernel,iterations=1)
display(erodesion)
# 膨胀操作
def dilate_(img):
kernel = np.ones((3,3),np.uint8)
erodesion = cv2.dilate(img,kernel,iterations=2)
display(erodesion)
# 开运算,先腐蚀后膨胀
def morphologyEx_open(img):
kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel,iterations=1)
display(opening)
# 闭运算,先膨胀后腐蚀
def morphologyEx_close(img):
kernel = np.ones((5,5),np.uint8)
closing = cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel,iterations=2)
display(closing)
# 梯度运算,膨胀-腐蚀
def gradient_(img):
kernel = np.ones((5,5),np.uint8)
gradient = cv2.morphologyEx(img,cv2.MORPH_GRADIENT,kernel)
display(gradient)
# 礼帽,原始-开运算
def morphologyEx_top_hat(img):
kernel = np.ones((5,5),np.uint8)
top_hat = cv2.morphologyEx(img,cv2.MORPH_TOPHAT,kernel,iterations=1)
display(top_hat)
# 黑帽,闭运算-原始
def morphologyEx_black_hat(img):
kernel = np.ones((5,5),np.uint8)
black_hat = cv2.morphologyEx(img,cv2.MORPH_BLACKHAT,kernel,iterations=1)
display(black_hat)
def main():
pic = "get1.png"
pic1 = "a.png"
img = cv2.imread(pic)
img1 = cv2.imread(pic1)
display(img)
erode_(img)
dilate_(img)
morphologyEx_open(img)
morphologyEx_close(img)
gradient_(img1)
morphologyEx_top_hat(img)
morphologyEx_black_hat(img)
if __name__ == "__main__":
main()
说明
背景黑色,内容白色如图所示,腐蚀,膨胀白色区域。
如果背景白色,内容黑色会相反。