膨胀
-求局部最大值
- 对目标像素点进行扩展
import cv2
img = cv2.imread("./images/4.jpg",cv2.IMREAD_GRAYSCALE)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
dst = cv2.dilate(img,kernel)
cv2.imshow("src",img)
cv2.imshow("dst",dst)
cv2.waitKey(0)
腐蚀
- 局部最小值
- 对目标像素点进行缩减
import cv2
img = cv2.imread("./images/4.jpg",cv2.IMREAD_GRAYSCALE)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
# 膨胀
# dst = cv2.dilate(img,kernel)
dst = cv2.erode(img,kernel)
cv2.imshow("src",img)
cv2.imshow("dst",dst)
cv2.waitKey(0)
开操作
- 先腐蚀后膨胀
- 以用来消除小物体,在纤细点处分离物体,并且在平滑较大物体的边界的同时不明显改变其面积(去除噪声及平滑目标边界)
import cv2
img = cv2.imread("./images/4.jpg",cv2.IMREAD_GRAYSCALE)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
# 膨胀
# dst = cv2.dilate(img,kernel)
# dst = cv2.erode(img,kernel)
dst = cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel)
cv2.imshow("src",img)
cv2.imshow("dst",dst)
cv2.waitKey(0)
闭操作
- 先膨胀再腐蚀
- 消除小型黑洞
import cv2
img = cv2.imread("./images/4.jpg",cv2.IMREAD_GRAYSCALE)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
# 膨胀
# dst = cv2.dilate(img,kernel)
# dst = cv2.erode(img,kernel)
dst = cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel)
# dst = cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel)
cv2.imshow("src",img)
cv2.imshow("dst",dst)
cv2.waitKey(0)
- 结果图
顶帽操作
- 原图像(减数)与“开运算”(被减数)的结果图之差。
- 拿到目标区域的噪音
import cv2
img = cv2.imread("./images/4.jpg",cv2.IMREAD_GRAYSCALE)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
# 膨胀
# dst = cv2.dilate(img,kernel)
# dst = cv2.erode(img,kernel)
# dst = cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel)
# dst = cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel)
# 顶帽
dst = cv2.morphologyEx(img,cv2.MORPH_TOPHAT,kernel)
cv2.imshow("src",img)
cv2.imshow("dst",dst)
cv2.waitKey(0)
黑帽操作
- 闭-原图拿到目标区域的洞
import cv2
img = cv2.imread("./images/4.jpg",cv2.IMREAD_GRAYSCALE)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
# 膨胀
# dst = cv2.dilate(img,kernel)
# dst = cv2.erode(img,kernel)
# dst = cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel)
# dst = cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel)
# 顶帽
# dst = cv2.morphologyEx(img,cv2.MORPH_TOPHAT,kernel)
dst = cv2.morphologyEx(img,cv2.MORPH_BLACKHAT,kernel)
cv2.imshow("src",img)
cv2.imshow("dst",dst)
cv2.waitKey(0)
梯度
- 获取梯度
import cv2
img = cv2.imread("./images/4.jpg",cv2.IMREAD_GRAYSCALE)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
# 膨胀
# dst = cv2.dilate(img,kernel)
# dst = cv2.erode(img,kernel)
# dst = cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel)
# dst = cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel)
# 顶帽
# dst = cv2.morphologyEx(img,cv2.MORPH_TOPHAT,kernel)
# dst = cv2.morphologyEx(img,cv2.MORPH_BLACKHAT,kernel)
dst = cv2.morphologyEx(img,cv2.MORPH_GRADIENT,kernel)
cv2.imshow("src",img)
cv2.imshow("dst",dst)
cv2.waitKey(0)