OPENCV盲打手撕代码默写练习-形态学

#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
Mat g_srcImage, g_dstImage;
int g_nElementShape = MORPH_RECT,g_nMaxIterationNum = 10,g_nOpenCloseNum = 0,g_nErodeDilateNum = 0,g_nTopBlackHatNum = 0,c;
static void on_OpenClose(int, void*){
	int offset = g_nOpenCloseNum - g_nMaxIterationNum;int Absolute_offset = offset > 0 ? offset : -offset;
	Mat element = getStructuringElement(g_nElementShape, Size(Absolute_offset*2+1, Absolute_offset*2+1), Point(Absolute_offset, Absolute_offset) );
	if( offset < 0 )morphologyEx(g_srcImage, g_dstImage, MORPH_OPEN, element);else morphologyEx(g_srcImage, g_dstImage, MORPH_CLOSE, element);
	imshow("【开/闭运算】",g_dstImage);
}
static void on_ErodeDilate(int, void*){
	int offset = g_nErodeDilateNum - g_nMaxIterationNum;int Absolute_offset = offset > 0 ? offset : -offset;
	Mat element = getStructuringElement(g_nElementShape, Size(Absolute_offset*2+1, Absolute_offset*2+1), Point(Absolute_offset, Absolute_offset) );
	if( offset < 0 )erode(g_srcImage, g_dstImage, element);else dilate(g_srcImage, g_dstImage, element);
	imshow("【腐蚀/膨胀】",g_dstImage);
}
static void on_TopBlackHat(int, void*){
	int offset = g_nTopBlackHatNum - g_nMaxIterationNum;int Absolute_offset = offset > 0 ? offset : -offset;
	Mat element = getStructuringElement(g_nElementShape, Size(Absolute_offset*2+1, Absolute_offset*2+1), Point(Absolute_offset, Absolute_offset) );
	if( offset < 0 )morphologyEx(g_srcImage, g_dstImage, MORPH_TOPHAT , element);else morphologyEx(g_srcImage, g_dstImage, MORPH_BLACKHAT, element);
	imshow("【顶帽/黑帽】",g_dstImage);
}
int main( ){
	g_srcImage = imread("head.jpg");namedWindow("【原始图】");imshow("【原始图】", g_srcImage);
	g_nOpenCloseNum=9;
	g_nErodeDilateNum=9;
	g_nTopBlackHatNum=2;
	namedWindow("【开/闭运算】",1);createTrackbar("迭代值", "【开/闭运算】",&g_nOpenCloseNum,g_nMaxIterationNum*2+1,on_OpenClose);
	namedWindow("【腐蚀/膨胀】",1);createTrackbar("迭代值", "【腐蚀/膨胀】",&g_nErodeDilateNum,g_nMaxIterationNum*2+1,on_ErodeDilate);
	namedWindow("【顶帽/黑帽】",1);createTrackbar("迭代值", "【顶帽/黑帽】",&g_nTopBlackHatNum,g_nMaxIterationNum*2+1,on_TopBlackHat);
	while(1){
		on_OpenClose(g_nOpenCloseNum, 0);
		on_ErodeDilate(g_nErodeDilateNum, 0);
		on_TopBlackHat(g_nTopBlackHatNum,0);
		c = waitKey(0);
		if( (char)c == 'q'||(char)c == 27 )	break;
		if( (char)c == '1' )g_nElementShape = MORPH_ELLIPSE;//椭圆
		else if( (char)c == '2' )g_nElementShape = MORPH_RECT;//矩形
		else if( (char)c == '3' )g_nElementShape = MORPH_CROSS;//十字
		else if( (char)c == ' ' )g_nElementShape = (g_nElementShape + 1) % 3;
	}
	return 0;
}//基本思路:先构造一个核(有三种形状),然后再执行运算,六个函数的应用(核心代码就两行)

猜你喜欢

转载自blog.csdn.net/cj1064789374/article/details/88833475