Search code examples
opencvimage-processingjavacv

Set rectangle style in OpenCV


I wish to know how many styles does OpenCV have for drawing detections. I wish know how to draw the rectangle like in this image:

enter image description here


Solution

  • OpenCV doesn't provide styles. You can only draw a rectangle with a given color, with 4/8 connected or with anti-aliasing points, with a given thickness.

    You can, however, simply draw 8 lines recovering the coordinates from the rectangle:

    enter image description here

    The code is pretty straightforward:

    #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;
    }