OpenCV实现halcon的shape_trans函数


enum ShapeTransType
{
    SHAPETRANS_RECTANGLE,	//平行于坐标轴的最小外接矩形
    SHAPETRANS_CIRCLE,		//最小外接圆
    SHAPETRANS_CONVER		//凸包
};

//功能:变换区域的形状
//参数:
//  src:输入图像
//  dst:输出图像
//  type:变换形状
//返回值:无
void shape_trans(Mat src, Mat &dst, ShapeTransType type)
{
    dst = Mat(src.size(), CV_8UC1, Scalar(0));
    vector<vector<Point>> contours;
    findContours(src, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
    int n = contours.size();
    for (int i = 0; i < n; i++)
    {
        if (type == SHAPETRANS_RECTANGLE)
        {
            Rect rect = boundingRect(contours[i]);
            rectangle (dst, rect, Scalar(255), CV_FILLED);
        }
        else if (type == SHAPETRANS_CIRCLE)
        {
            Point2f center;
            float radius;
            minEnclosingCircle(contours[i], center, radius);
            circle (dst, center, radius, Scalar(255), CV_FILLED);
        }
        else if (type == SHAPETRANS_CONVER)
        {
            vector<Point> conver;
            convexHull(contours[i], conver);

            vector<vector<Point>> pconver;
            pconver.push_back(conver);

            fillPoly(dst, pconver, Scalar(255));
        }
    }
}

你可能感兴趣的:(OpenCV,opencv)