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);
Mat& img
The image on which the rectangle will be drawn.
Point pt1
The first vertex of the rectangle (usually the top-left corner).
Point pt2
The opposite vertex of the rectangle (usually the bottom-right corner).
Scalar color
The color of the rectangle in BGR format. Example: Scalar(255, 0, 0)
is blue.
int thickness
Thickness of the lines. Use FILLED
or -1
to fill the rectangle.
int lineType
LINE_8
– 8-connected line (default)LINE_4
– 4-connected lineLINE_AA
– Anti-aliased lineint shift
Number of fractional bits in the point coordinates. Typically 0
.
#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;
}
Use thickness = FILLED
or -1
to create a solid filled rectangle.
Use lineType = LINE_AA
for smoother rectangle edges, particularly for display or image generation.
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));