#include
#include
#include
#include
using namespace std;
using namespace cv;
//全局变量声明
Mat g_srcImage, g_dstImage;
int g_nElementShape=MORPH_RECT;//元素结构形状
int g_nMaxIterationNum = 10;
int g_nOpenCloseNum = 0;//
int g_nErordeDilateNum = 0;//
int g_nTopBlackHatNum = 10;//
//轨迹条回调函数
static void on_OpenClose(int, void*);
static void on_ErodeDilate(int, void*);
static void on_TopBlackHat(int, void*);
static void on_ShowHelpText(int, void*);
static void Showhelptext();//显示帮助文字
int main(){
system("color 5E");
g_srcImage = imread("靶标原图.png", 1);
if (!g_srcImage.data){
printf("打开图片错误,请检查路径\n");
return false;
}
namedWindow("原图窗口", 1);
imshow("原图窗口", g_srcImage);
//开闭运算
namedWindow("开闭运算", 1);
createTrackbar("迭代值", "开闭运算", &g_nOpenCloseNum,g_nMaxIterationNum*2+1,on_OpenClose);
//腐蚀与膨胀
namedWindow("腐蚀膨胀", 1);
createTrackbar("迭代值", "腐蚀膨胀", &g_nErordeDilateNum,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_nErordeDilateNum, 0);
on_TopBlackHat(g_nTopBlackHatNum, 0);
int c = waitKey(0);
if ((char)c == 'q' || (char)c == 27)//presh the button q or ESC
break;
if ((char)c == 49)
g_nErordeDilateNum = MORPH_ELLIPSE;//presh the button 1
if ((char)c == 50)
g_nElementShape = MORPH_RECT;
if ((char)c == 51)
g_nElementShape = MORPH_CROSS;
else if ((char)c == ' ')
g_nElementShape = (g_nElementShape + 1) % 3;
}
return 0;
}
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_nErordeDilateNum - 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
{
erode(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);
}