OpenCV形态学处理
- 1、膨胀
- 2、腐蚀
- 3、开/闭运算
- 4、示例
膨胀、腐蚀、开运算、闭运算
1、膨胀
膨胀就是求局部最大值的操作,膨胀的数学表达式:
dst
(
x
,
y
)
=
max
(
x
′
,
y
′
)
:
=
1
ement
(
x
′
,
y
′
)
≠
0
src
(
x
+
x
′
,
y
+
y
′
)
\operatorname{dst}(x, y)=\max _{\left(x^{\prime}, y^{\prime}\right):=1 \operatorname{ement}\left(x^{\prime}, y^{\prime}\right) \neq 0} \operatorname{src}\left(x+x^{\prime}, y+y^{\prime}\right)
dst(x,y)=(x′,y′):=1ement(x′,y′)=0maxsrc(x+x′,y+y′)
核心代码:
//获取自定义核
cv::Mat element = cv::getStructuringElement(MORPH_RECT, Size(5, 5));
//进行膨胀操作
cv::dilate(image, out, element);
2、腐蚀
腐蚀就是求局部最小值的操作,腐蚀的数学表达式:
dst
(
x
,
y
)
=
min
(
x
′
,
y
′
)
:
=
1
ement
(
x
′
,
y
′
)
≠
0
src
(
x
+
x
′
,
y
+
y
′
)
\operatorname{dst}(x, y)=\min _{\left(x^{\prime}, y^{\prime}\right):=1 \operatorname{ement}\left(x^{\prime}, y^{\prime}\right) \neq 0} \operatorname{src}\left(x+x^{\prime}, y+y^{\prime}\right)
dst(x,y)=(x′,y′):=1ement(x′,y′)=0minsrc(x+x′,y+y′)
核心代码:
//获取自定义核
cv::Mat element = cv::getStructuringElement(MORPH_RECT, Size(5, 5));
//进行腐蚀操作
cv::erode(image,out, element);
3、开/闭运算
- 开运算(Opening Operation),其实就是先腐蚀后膨胀的过程。其数学表达式如下:
dst = open ( src , element ) = dilate ( erode ( src , element ) ] \text { dst }=\operatorname{open}(\operatorname{src}, \text { element })=\operatorname{dilate}(\text { erode }(\operatorname{src}, \text { element })] dst =open(src, element )=dilate( erode (src, element )]
开运算可以用来消除小物体、在纤细点处分离物体、平滑较大物体的边界的同时并不明显改变其面积。 - 先膨胀后腐蚀的过程称为闭运算(Closing Operation),其数学表达式如下:
dst = close ( src , element ) = erode ( dilate ( src , element ) ] \text { dst }=\operatorname{close}(\operatorname{src}, \text { element })=\operatorname{erode}(\text { dilate}(\operatorname{src}, \text { element })] dst =close(src, element )=erode( dilate(src, element )]
闭运算能够排除小型黑洞(黑色区域) - 闭运算核心代码:
cv::Mat element = cv::getStructuringElement(cv::MORPH_RECT, Size(3, 3));
cv::Mat result;
cv::morphologyEx(test, result, cv::MORPH_CLOSE, element);
- 开运算核心代码:
cv::Mat element = cv::getStructuringElement(cv::MORPH_RECT, Size(3, 3));
cv::Mat result;
cv::morphologyEx(test, result, cv::MORPH_OPEN, element);
4、示例
原始图像:
闭运算后: