2020.10.31 使用OpenCV进行图像的腐蚀膨胀操作【OpenCV C++】

腐蚀膨胀处理练习

源代码:

// testOpencv09.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;

Mat src, dst;
const char* inputWindow = "input window";
const char* outputWindow = "output window";

int elementSize = 12;
int maxSize = 50;
void CallBackDemo(int,void*);

int main()
{
    //std::cout << "Hello World!\n";
    
    src = imread("E:/imageSources/4.jpg");
    if (!src.data) {
        printf("can not load image");
        return -1;
    }

    namedWindow(inputWindow,WINDOW_AUTOSIZE);
    imshow(inputWindow,src);
    namedWindow(outputWindow, WINDOW_AUTOSIZE);
    createTrackbar("Element Size:" , outputWindow,&elementSize,maxSize,CallBackDemo);
    CallBackDemo(0, 0);

    waitKey(0);
    return 0;

}

void CallBackDemo(int, void*) {
    //为什么s = elementSize*2+1 ?
    //应为如果s直接等于elementSize的话,如果为偶数,会出现错误
    //这样的作法式保证s的值始终为奇数
    int s = elementSize*2+1;
    //获取需要结构元素
    Mat structureElement = getStructuringElement(MORPH_CROSS,Size(s,s),Point(-1,-1));
    //膨胀
    dilate(src,dst,structureElement,Point(-1,-1),1);
    //腐蚀
    //erode(src, dst, structureElement);
    imshow(outputWindow,dst);
    return;
}

腐蚀效果(自行调节结构元素大小):

2020.10.31 使用OpenCV进行图像的腐蚀膨胀操作【OpenCV C++】

膨胀效果:

2020.10.31 使用OpenCV进行图像的腐蚀膨胀操作【OpenCV C++】