原图
结果图
//包含头文件
#include <opencv2/opencv.hpp>//命名空间
using namespace cv;
using namespace std;//全局函数声明部分//我的腐蚀运算
Mat Erode(Mat src, Mat Mask, uint32_t x0, uint32_t y0)
{uint32_t x = 0, y = 0;Mat dst(src.rows, src.cols, CV_8U, Scalar(0));for (x = 0; x < src.cols; ++x){for (y = 0; y < src.rows; ++y){uint8_t dst_P = 255;for (uint32_t xm = 0; xm < Mask.cols; ++xm){for (uint32_t ym = 0; ym < Mask.rows; ++ym){if (dst_P && Mask.at<uchar>(Point(xm, ym)) && (x + xm) < src.cols && (y + ym) < src.rows)if (dst_P > src.at<uchar>(Point(x + xm, y + ym))) //寻找最小值dst_P = src.at<uchar>(Point(x + xm, y + ym));}if (!dst_P)break;}if (dst_P && (x + x0) < src.cols && (y + y0) < src.rows)dst.at<uchar>(Point(x + x0, y + y0)) = dst_P;}}return dst;
}//我的膨胀运算
Mat Dilate(Mat src, Mat Mask, uint32_t x0, uint32_t y0)
{uint32_t x = 0, y = 0;Mat dst(src.rows, src.cols, CV_8U, Scalar(0));for (x = 0; x < src.cols; ++x){for (y = 0; y < src.rows; ++y){uint8_t dst_P = 0;for (uint32_t xm = 0; xm < Mask.cols; ++xm){for (uint32_t ym = 0; ym < Mask.rows; ++ym){if (dst_P != 255 && Mask.at<uchar>(Point(xm, ym)) && (x + xm) < src.cols && (y + ym) < src.rows)if (dst_P < src.at<uchar>(Point(x + xm, y + ym))) //寻找最大值dst_P = src.at<uchar>(Point(x + xm, y + ym));}if (dst_P == 255)break;}if (dst_P && (x + x0) < src.cols && (y + y0) < src.rows)dst.at<uchar>(Point(x + x0, y + y0)) = dst_P;}}return dst;
}//主函数
int main(int argc, char* argv[])
{//【1】载入图像,灰度化Mat image = imread("2.png", 0);//灰度原图//【2】检查是否载入成功if (image.empty()){printf("读取图片错误,请确认目录下是否有imread函数指定图片存在!\n");return 0;}//【3】生成结构元素uint8_t element_a[7][7] ={ 1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1, };Mat element = Mat(7, 7, CV_8U, element_a);//【4】显示图像imshow("原灰度图像", image);//【5】腐蚀运算Mat erodedImage;erode(image, erodedImage, element);imshow("Opencv的腐蚀运算", erodedImage);imshow("我的腐蚀运算", Erode(image, element, 3, 3));//【6】膨胀运算Mat dilatedImage;dilate(image, dilatedImage, element);imshow("Opencv的膨胀运算", dilatedImage);imshow("我的膨胀运算", Dilate(image, element, 3, 3));//【7】开运算Mat OpenImage;morphologyEx(image, OpenImage, MORPH_OPEN, element);imshow("Opencv的开运算", OpenImage);imshow("我的开运算", Dilate(Erode(image, element, 3, 3), element, 3, 3)); //开运算即先腐蚀再膨胀//【8】闭运算Mat CloseImage;morphologyEx(image, CloseImage, MORPH_CLOSE, element);imshow("Opencv的闭运算", CloseImage);imshow("我的闭运算", Erode(Dilate(image, element, 3, 3), element, 3, 3)); //闭运算即先膨胀再腐蚀//【10】保持窗口显示waitKey(0);return 0;
}