在OpenCV中设置矩形样式

时间:2016-03-10 23:27:32

标签: opencv image-processing javacv

我想知道OpenCV有多少样式用于绘制检测。我希望知道如何在这张图片中绘制矩形:

enter image description here

1 个答案:

答案 0 :(得分:1)

OpenCV不提供样式。您只能绘制具有给定颜色的矩形,连接4/8或具有给定厚度的抗锯齿点。

但是,您可以简单地绘制8条线来恢复矩形中的坐标:

enter image description here

代码很简单:

#include <opencv2/opencv.hpp>
using namespace cv;

void drawDetection(Mat3b& img, const Rect& r, Scalar color = Scalar(0,255,0), int thickness = 3)
{
    int hor = r.width / 7;
    int ver = r.height / 7;

    // Top left corner
    line(img, r.tl(), Point(r.x, r.y + ver), color, thickness);
    line(img, r.tl(), Point(r.x + hor, r.y), color, thickness);

    // Top right corner
    line(img, Point(r.br().x - hor, r.y), Point(r.br().x, r.y), color, thickness);
    line(img, Point(r.br().x, r.y + ver), Point(r.br().x, r.y), color, thickness);

    // Bottom right corner
    line(img, Point(r.br().x, r.br().y - ver), r.br(), color, thickness);
    line(img, Point(r.br().x - hor, r.br().y), r.br(), color, thickness);

    // Bottom left corner
    line(img, Point(r.x, r.br().y - ver), Point(r.x, r.br().y), color, thickness);
    line(img, Point(r.x + hor, r.br().y), Point(r.x, r.br().y), color, thickness);
}

int main()
{
    // Load image
    Mat3b img = imread("path_to_image");

    // Your detection
    Rect detection(180, 160, 220, 240);

    // Custom draw
    drawDetection(img, detection);

    imshow("Detection", img);
    waitKey();

    return 0;
}