# OpenCV 形态学操作

10 篇文章 0 订阅

### 1.腐蚀

import cv2
import numpy as np
kernel = np.ones((3,3),np.uint8)
erosion = cv2.erode(img,kernel,iterations = 1)
cv2.imshow('erosion', erosion)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

### 2.膨胀

import cv2
import numpy as np
kernel = np.ones((3,3),np.uint8)
dige_erosion = cv2.erode(img,kernel,iterations = 1)
kernel = np.ones((5,5),np.uint8)
dige_dilate = cv2.dilate(dige_erosion,kernel,iterations = 1)
cv2.imshow('dilate', dige_dilate)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

### 3.通用形态学函数

OpenCV提供了函数cv2.morphologyEx()来实现上述形态学运算。

### 开运算：先腐蚀后膨胀

import cv2
import numpy as np
# 开：先腐蚀，再膨胀
kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
cv2.imshow('opening', opening)
cv2.waitKey(0)
cv2.destroyAllWindows()

### 闭运算：先膨胀后腐蚀

import cv2
import numpy as np
# 闭：先膨胀，再腐蚀
kernel = np.ones((5,5),np.uint8)
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
cv2.imshow('closing', closing)
cv2.waitKey(0)
cv2.destroyAllWindows()

### 礼帽运算：原始图像 - 开运算

import cv2
import numpy as np
#礼帽
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
cv2.imshow('tophat', tophat)
cv2.waitKey(0)
cv2.destroyAllWindows()

### 黑帽运算：闭运算 - 原始图像

import cv2
import numpy as np
#黑帽
blackhat  = cv2.morphologyEx(img,cv2.MORPH_BLACKHAT, kernel)
cv2.imshow('blackhat', blackhat )
cv2.waitKey(0)
cv2.destroyAllWindows()

### 4.核函数

import cv2
import numpy as np
img_cvt = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,img_thr = cv2.threshold(img_cvt,150,255,cv2.THRESH_BINARY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(14,1))
dst1 = cv2.dilate(img_thr,kernel,iterations=1)
kernel2 = cv2.getStructuringElement(cv2.MORPH_RECT,(1,14))
dst2 =cv2.dilate(img_thr,kernel2,iterations=1)
dst=cv2.bitwise_and(dst2,dst1)
cv2.imshow("img_cvt",img_cvt)
cv2.imshow("dst",dst)
cv2.imwrite("dst.jpg",dst)
cv2.waitKey(0)
cv2.destroyAllWindows()

### 实践：

import cv2
import numpy as np
def show(name,img):
cv2.imshow(name,img)
cv2.waitKey(0)
cv2.destroyAllWindows()
img=cv2.imread("xuexi.jpg",0)
h,w=img.shape
src=cv2.resize(img,(int(w/3),int(h/3)))
show('src',src)
binary = cv2.threshold(src,200,255,0)[1]
show('binary',binary)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(45,1))
DilateImg =cv2.dilate(binary,kernel)
result=cv2.morphologyEx(src,cv2.MORPH_BLACKHAT,kernel)
dst=cv2.bitwise_not(result)
show("dst",dst)

06-21 180
03-11 100
04-08 254
07-11 530
02-04 2821
01-16 408
02-15 1904
01-13 262

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

wx_57556

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。