上一节中我们也说过:
1. 开操作是先腐蚀、后膨胀处理。
2. 闭操作是先膨胀、后腐蚀处理。
也就是说开操作可以这样实现:
cv::erode(result,result,cv::Mat());
cv::dilate(image,result,cv::Mat());
闭操作就是把顺序颠倒过来。
但是OpenCV中有专门的形态学算子:
C++: void morphologyEx(InputArray src, OutputArray dst, int op, InputArray kernel, Point anchor=Point(-1,-1), int iterations=1, int borderType=BORDER_CONSTANT, const Scalar& borderValue=morphologyDefaultBorderValue() )
src– Source image. The number of channels can be arbitrary. The depth should be one of
CV_8U, CV_16U, CV_16S, CV_32F‘ or ‘‘CV_64F.
dst – Destination image of the same size and type as src .
element – Structuring element.
op – Type of a morphological operation that can be one of the following:
– MORPH_OPEN - an opening operation
– MORPH_CLOSE - a closing operation
– MORPH_GRADIENT - a morphological gradient
– MORPH_TOPHAT - “top hat”
– MORPH_BLACKHAT - “black hat”
iterations – Number of times erosion and dilation are applied.
borderType – Pixel extrapolation method. See borderInterpolate() for details.
borderValue – Border value in case of a constant border. The default value has a special meaning. See createMorphologyFilter() for details.
原图(二值图像)
闭操作
开操作
先闭后开操作
从图中可以看出闭操作将白色区域被连接起来了,或者被扩大了。任何黑色区域如果小于结构元素的大小都会被消除
相反的,开操作消除了白点,这些白点的大小都小于结构元素。
这两种操作通常用在目标检测中。闭操作将错误分开成小片的物体从新连接成一个整体。而开操作则是去除一小块的噪点。因此,他们两个结合起来用效果会更好。先闭操作然后再开操作,最后的结果就是得到了图像中我们想要的目标。
也可以先进性开操作,然后再闭操作。但是这样做可能会消除更多的碎块。
值得注意的是对于同一幅图像连续使用开操作或者闭操作是没有任何意义的,操作结果都和第一次的相同。
#include
#include
#include
int main()
{
cv::Mat img = cv::imread("tower.jpg");
cv::Mat cvtcolor;
cv::Mat result;
cv::cvtColor(img, cvtcolor, CV_RGB2GRAY);
if(!img.data)
return 0;
/* cv::imshow("img", img);
cv::imshow("cvtcolor", cvtcolor)*/;
cv::threshold(cvtcolor, result, 100, 255, CV_THRESH_BINARY);
cv::imshow("result", result);
cv::Mat element5(5,5,CV_8U,cv::Scalar(1));
cv::Mat closed;
cv::morphologyEx(result, closed, cv::MORPH_CLOSE, element5);
cv::imshow("closed", closed);
cv::Mat opened;
cv::morphologyEx(result, opened, cv::MORPH_OPEN, element5);
cv::imshow("opened", opened);
cv::Mat closeopened;
cv::morphologyEx(closed, closeopened, cv::MORPH_OPEN, element5);
cv::imshow("closedopened", closeopened);
cv::waitKey();
}