Morphological Transformations html
腐蚀的基本思想:侵蚀前景物体的边界(老是试图保持前景为白色);内核在图像中滑动(如在2D卷积中).只有当内核下的全部像素都是1时,原始图像中的像素(1或0)才会被认为是1,不然它会被侵蚀(变为零).函数
边界附近的全部像素都将被丢弃,具体取决于内核的大小.所以,前景对象的厚度或大小减少,或者图像中的白色区域减少.
它有助于消除小的白噪声,分离两个链接的对象
原图:ui
代码:spa
import cv2 import numpy as np img = cv2.imread('img7.png',0) kernel = np.ones((5,5),np.uint8) erosion = cv2.erode(img,kernel,iterations = 1) cv2.imshow('src',img) cv2.imshow('show',erosion) cv2.waitKey()
效果图:code
它刚好与侵蚀相反。 这里,若是内核下的至少一个像素为“1”,则像素元素为“1”. 所以它增长了图像中的白色区域或前景对象的大小增长.
一般,在去除噪音的状况下,腐蚀以后是膨胀.由于,侵蚀会消除白噪声,但它也会缩小咱们的物体,因此咱们膨胀它,因为噪音消失了,它们不会再回来,则咱们的物体区域会增长。 它也可用于链接对象的破碎部分.orm
代码:htm
import cv2 import numpy as np img = cv2.imread('img7.png',0) kernel = np.ones((5,5),np.uint8) dilation = cv2.dilate(img,kernel,iterations = 1) cv2.imshow('src',img) cv2.imshow('show',dilation) cv2.waitKey()
cv2.morphologyEx()
:先腐蚀再膨胀,有助于消除噪音.
代码:对象
import cv2 import numpy as np import matplotlib.pylab as plt img = cv2.imread('img8.png',0) kernel = np.ones((5,5),np.uint8) opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel) cv2.imshow('src',img) cv2.imshow('show',opening) cv2.waitKey()
先膨胀后腐蚀,用于消除前景对象内的小孔或对象上的小黑点.
代码:blog
import cv2 import numpy as np img = cv2.imread('img9.png',0) kernel = np.ones((5,5),np.uint8) closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel) cv2.imshow('src',img) cv2.imshow('show',closing) cv2.waitKey()
图像的膨胀和腐蚀之间的差别,结果看起来像目标的轮廓
代码:ip
import cv2 import numpy as np img = cv2.imread('img7.png',0) kernel = np.ones((5,5),np.uint8) gradient = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel) cv2.imshow('src',img) cv2.imshow('show',gradient) cv2.waitKey()
原图像与开运算图的区别,突出原图像中比周围亮的区域
代码:
import cv2 import numpy as np img = cv2.imread('img7.png',0) kernel = np.ones((5,5),np.uint8) tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel) cv2.imshow('src',img) cv2.imshow('show',tophat) cv2.waitKey()
闭运算图 - 原图像,突出原图像中比周围暗的区域
代码:
import cv2 import numpy as np img = cv2.imread('img7.png',0) kernel = np.ones((5,5),np.uint8) blackhat = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel) cv2.imshow('src',img) cv2.imshow('show',blackhat) cv2.waitKey()
咱们在Numpy的帮助下建立了前面示例中的矩形结构元素. 但在某些状况下,可能须要椭圆/圆形内核。 因此为此,OpenCV有一个函数cv2.getStructuringElement()
. 只需传递内核的形状和大小,便可得到所需的内核.
代码:
# Rectangular Kernel cv2.getStructuringElement(cv2.MORPH_RECT,(5,5)) Out[4]: array([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]], dtype=uint8) # Elliptical Kernel cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)) Out[5]: array([[0, 0, 1, 0, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0]], dtype=uint8) # Cross-shaped Kernel cv2.getStructuringElement(cv2.MORPH_CROSS,(5,5)) Out[6]: array([[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [1, 1, 1, 1, 1], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0]], dtype=uint8)