OpenCV对图片中的RotatedRect进行填充

函数名:full_rotated_rect

函数参数: image输入图像,rect希望在图像中填充的RotatedRect,color填充的颜色

主要的思路是:先找到RotatedRect的四个顶点,然后画出外框。再利用四个顶点找出其中平行两边的所有点,对相应的两个点进行连接。

void full_rotated_rect(Mat &image, const RotatedRect &rect, const Scalar &color)
{
    CvPoint2D32f point[4];
    Point pt[4];
    vector<Point> center1, center2;

    /*画出外框*/
    cvBoxPoints(rect, point);
    for (int i = 0; i<4; i++)
    {
        pt[i].x = (int)point[i].x;
        pt[i].y = (int)point[i].y;
    }
    line(image, pt[0], pt[1], color, 1);
    line(image, pt[1], pt[2], color, 1);
    line(image, pt[2], pt[3], color, 1);
    line(image, pt[3], pt[0], color, 1);

    /*填充内部*/
    find_all_point(pt[0], pt[1], center1);  /*找出两点间直线上的所有点*/
    find_all_point(pt[3], pt[2], center2);
    vector<Point>::iterator itor1 = center1.begin(), itor2 = center2.begin();
    while (itor1 != center1.end() && itor2 != center2.end())
    {
        line(image, *itor1, *itor2, color, 1);  /*连接对应点*/
        itor1++;
        itor2++;
    }

    vector<Point>().swap(center1);
    vector<Point>().swap(center2);
}

函数名:find_all_point

函数参数:start起始点,end结束点,save保存点的容器

主要思路:递归查找两点的中点,直到两点相同。

void find_all_point(Point start, Point end, vector<Point> &save)
{
    if (abs(start.x - end.x) <= 1 && abs(start.y - end.y) <= 1)
    {
        save.push_back(start);
        return; /*点重复时返回*/
    }

    Point point_center;
    point_center.x = (start.x + end.x) / 2;
    point_center.y = (start.y + end.y) / 2;
    save.push_back(point_center);   /*储存中点*/
    find_all_point(start, point_center, save);  /*递归*/
    find_all_point(point_center, end, save);
}

原图:                                                     填充后:

猜你喜欢

转载自blog.csdn.net/wizardtoh/article/details/44850863