我几乎没有行Matlab代码来应用八边形形状的结构化元素。我想将相同的代码转换为opencv cpp。
Matlab代码
se1 = strel('octagon',3);
imgNew = imerode(image,se1);
Opencv Cpp代码
我知道我们可以创建一个结构元素,然后必须调用erode函数,但是如何在opencv中创建八边形结构元素。
element = ??
erode(image,dst,element);
如何在opencv中创建Octagon结构元素?
最佳答案
一种简单的方法是计算八边形的顶点,并使用fillConvexPoly
绘制八边形。M
必须为3的非负倍数(如在Matlab中一样)。
代码
#include <opencv2\opencv.hpp>
#include <vector>
using namespace std;
using namespace cv;
Mat1b getOctagon(int M)
{
// M positive and multiple of 3
CV_Assert((M > 0) && ((M % 3) == 0));
int k = M / 3;
int rows = M*2 + 1;
int cols = M*2 + 1;
Point c(M, M);
Mat1b strel(rows, cols, uchar(0));
// Octagon vertices
// 0-1
// / \
// 7 2
// | c |
// 6 3
// \ /
// 5-4
vector<Point> vertices(8);
vertices[0].x = c.x - k;
vertices[0].y = 0;
vertices[1].x = c.x + k;
vertices[1].y = 0;
vertices[2].x = cols-1;
vertices[2].y = c.y - k;
vertices[3].x = cols-1;
vertices[3].y = c.y + k;
vertices[4].x = c.x + k;
vertices[4].y = rows-1;
vertices[5].x = c.x - k;
vertices[5].y = rows-1;
vertices[6].x = 0;
vertices[6].y = c.y + k;
vertices[7].x = 0;
vertices[7].y = c.y - k;
fillConvexPoly(strel, vertices, Scalar(1));
return strel;
}
int main()
{
Mat1b kernel = getOctagon(3);
//morphologyEx(src, dst, MORPH_ERODE, kernel);
return 0;
}
结果
M = 3:
M = 12: