Overview of `cv::rectangle` in OpenCV

The cv::rectangle() function in OpenCV is used to draw rectangles on images. It can draw both filled and outlined rectangles.

Its core usage syntax is:

cv::rectangle(Mat& img, Point pt1, Point pt2, const Scalar& color,
             int thickness = 1, int lineType = LINE_8, int shift = 0);

Parameters of `cv::rectangle()`

1. Mat& img

The image on which the rectangle will be drawn.

2. Point pt1

The first vertex of the rectangle (usually the top-left corner).

3. Point pt2

The opposite vertex of the rectangle (usually the bottom-right corner).

4. Scalar color

The color of the rectangle in BGR format. Example: Scalar(255, 0, 0) is blue.

5. int thickness

Thickness of the lines. Use FILLED or -1 to fill the rectangle.

6. int lineType

7. int shift

Number of fractional bits in the point coordinates. Typically 0.

Example Usage

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

int main() {
    Mat image = Mat::zeros(400, 400, CV_8UC3);

    // Draw a blue rectangle with thickness 2
    rectangle(image, Point(50, 50), Point(300, 300), Scalar(255, 0, 0), 2);

    // Draw a filled red rectangle
    rectangle(image, Point(100, 100), Point(200, 200), Scalar(0, 0, 255), FILLED);

    imshow("Rectangles", image);
    waitKey(0);
    return 0;
}

Advanced Notes

Filled Rectangle

Use thickness = FILLED or -1 to create a solid filled rectangle.

Anti-Aliased Edges

Use lineType = LINE_AA for smoother rectangle edges, particularly for display or image generation.

Use with ROI

cv::Rect can also define a region of interest, and be used with rectangle like:

Rect roi(60, 60, 100, 150);
rectangle(image, roi, Scalar(0, 255, 0));