Opencv2.4学习::形态学处理(三)形态学梯度、顶帽、黑帽

形态学处理(三)


1、腐蚀、膨胀操作

2、开运算、闭运算

3、形态学梯度、顶帽、黑帽


形态学梯度

形态学梯度实为膨胀图与腐蚀图之差。

作用:

  • 突出高亮区域的外围
  • 为轮廓查找提供新思路

测试代码:

#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<iostream>
using namespace std;
using namespace cv;
void main()
{
	Mat srcImg = imread("F:\\opencv_re_learn\\hand.jpg");
	if (!srcImg.data){
		cout << "failed to read" << endl;
		system("pause");
		return;
	}
	imshow("src", srcImg);
	Mat srcGray;
	cvtColor(srcImg, srcGray, CV_BGR2GRAY);
	Mat thresh;
	threshold(srcGray, thresh, 230, 255, CV_THRESH_BINARY_INV);
	imshow("thresh", thresh);
	//自定义核
	Mat element = getStructuringElement(MORPH_RECT,
		Size(5, 5));
	//形态学梯度
	Mat gradient_result;
	morphologyEx(thresh, gradient_result, MORPH_GRADIENT, element);
	imshow("形态学梯度", gradient_result);
	waitKey(0);
}

实现效果:

 


顶帽

原图像与“开运算“的结果图之差

作用:

  • 用于背景提取
  • 顶帽运算往往用来分离比邻近点亮一些的斑块。当一幅图像具有大幅的背景的时候,而微小物品比较有规律的情况下,可以使用顶帽运算进行背景提取。【引用自:https://blog.csdn.net/poem_qianmo/article/details/24599073
  •  

测试代码:

#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<iostream>
using namespace std;
using namespace cv;
void main()
{
	Mat srcImg = imread("F:\\opencv_re_learn\\test.jpg");
	if (!srcImg.data){
		cout << "failed to read" << endl;
		system("pause");
		return;
	}
	imshow("src", srcImg);
	Mat srcGray;
	cvtColor(srcImg, srcGray, CV_BGR2GRAY);
	Mat thresh;
	threshold(srcGray, thresh, 230, 255, CV_THRESH_BINARY_INV);
	imshow("thresh", thresh);
	//自定义核
	Mat element = getStructuringElement(MORPH_RECT,
		Size(5, 5));
	//顶帽
	Mat tophat_result;
	morphologyEx(thresh, tophat_result, MORPH_TOPHAT, element);
	imshow("顶帽", tophat_result);
	waitKey(0);
}

实现效果:

再进一步,既然已经可以提取这个图的背景,那么通过背景与二值化图像异或,即可提取前景。

需在上面代码后添加如下:

	Mat bit_xor;
	bitwise_xor(thresh, tophat_result, bit_xor);
	imshow("异或", bit_xor);

实现效果:


黑帽

原图像与“闭运算“的结果图之差

作用:

  • 暂未找到好的例子

猜你喜欢

转载自blog.csdn.net/dieju8330/article/details/83901693