"
1 #include
2 #include
3 #include
4 #include
5 #include
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[span style=""color: rgba(128, 0, 128, 1)"">0||xi>= bin.cols|| yi[span style=""color: rgba(128, 0, 128, 1)"">0 || yi >= bin.rows){
21 continue;
22 }
23
24 maxV = (std::max)(maxV, bin.at(yi, xi));
25 }
26 }
27 img1.at(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++) { //代码效果参考:https://v.youku.com/v_show/id_XNjQwNjYzNDk0NA==.html
42 if (xi[span style=""color: rgba(128, 0, 128, 1)"">0||xi>= bin.cols|| yi[span style=""color: rgba(128, 0, 128, 1)"">0 || yi >= bin.rows){
43 continue;
44 }
45 minV = (std::min)(minV, bin.at(yi, xi));
46
47 }
48 }
49 img1.at(i, j) = minV;
50 }
51 }
52 }
53 int main()
54 {
55 //从文件中读取成灰度图像
56
57
58 Mat img1 = imread("""",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//代码效果参考:https://v.youku.com/v_show/id_XNjQwNjY0NTcyMA==.html
);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函数法:
自己函数:
萍水相逢逢萍水,浮萍之水水浮萍!
"