1 #include <opencv2/opencv.hpp> 2 #include <opencv2/core/core.hpp> 3 #include <opencv2/highgui/highgui.hpp> 4 #include<iostream> 5 #include<stdlib.h> 6 using namespace cv; 7 using namespace std; 8 9 //自定义膨胀函数 10 void dilated_my( Mat img1,Mat bin,int k) 11 { 12 k=(k-1)/2; 13 for (int i = 0; i < bin.rows; ++i){ 14 for (int j = 0; j < bin.cols; ++j){ 15 16 uchar maxV = 0; 17 //遍历周围最大像素值 18 for (int yi = i-k; yi <= i+k; yi++) { 19 for (int xi = j-k; xi <= j+k; xi++) { 20 if (xi<0||xi>= bin.cols|| yi<0 || yi >= bin.rows){ 21 continue; 22 } 23 24 maxV = (std::max<uchar>)(maxV, bin.at<uchar>(yi, xi)); 25 } 26 } 27 img1.at<uchar>(i, j) = maxV; 28 } 29 } 30 } 31 //自定义腐蚀函数 32 void eroded_my( Mat img1,Mat bin ,int k) 33 { 34 k=(k-1)/2; 35 for (int i = 0; i < bin.rows; ++i){ 36 for (int j = 0; j < bin.cols; ++j){ 37 uchar minV = 255; 38 39 //遍历周围最小像素值 40 for (int yi = i-k; yi <= i+k; yi++) { 41 for (int xi = j-k; xi <= j+k; xi++) { 42 if (xi<0||xi>= bin.cols|| yi<0 || yi >= bin.rows){ 43 continue; 44 } 45 minV = (std::min<uchar>)(minV, bin.at<uchar>(yi, xi)); 46 47 } 48 } 49 img1.at<uchar>(i, j) = minV; 50 } 51 } 52 } 53 int main() 54 { 55 //从文件中读取成灰度图像 56 57 58 Mat img1 = imread("E://txm.jpg",0); 59 imshow("gray",img1); 60 Mat dst1; 61 Mat dst2; 62 Mat bin; 63 threshold(img1,bin,200,255,CV_THRESH_BINARY); 64 65 //opencv函数法 66 Mat structElement1 = getStructuringElement(MORPH_RECT, Size(5,5)); 67 dilate(bin,dst1,structElement1); 68 imshow("opencv_dilated", dst1); 69 erode(bin,dst2,structElement1); 70 imshow("opencv_eroded", dst2); 71 72 //自定义方法 73 dilated_my(img1,bin,5); 74 imshow("my_dilated",img1); 75 eroded_my(img1,bin,5); 76 imshow("my_eroded",img1); 77 78 waitKey(0); 79 return 0; 80 81 }
原图:
opencv函数法:
自己函数: