Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw rectangle in OpenCV

Tags:

c++

opencv

I want to draw a rectangle in OpenCV by using this function:

rectangle(Mat& img, Rect rec, const Scalar& color, int thickness=1, int lineType=8, int shift=0 )

But when I use it I am facing some errors. My question is: can anyone explain the function with an example? I found some examples but with another function:

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

This example on the second function:

rectangle(image, pt2, pt1, Scalar(0, 255, 0), 2, 8, 0);

This function I understand, but with the first function I'm facing a problem in parameter Rect. I don't know how I can deadlier it?

like image 594
Adel Khatem Avatar asked Oct 19 '16 01:10

Adel Khatem


People also ask

How do you draw a rectangle in OpenCV?

In this program, we will draw a rectangle using the OpenCV function rectangle(). This function takes some parameters like starting coordinates, ending coordinates, color and thickness and the image itself.


1 Answers

The cv::rectangle function that accepts two cv::Point's takes both the top left and the bottom right corner of a rectangle (pt1 and pt2 respectively in the documentation). If that rectangle is used with the cv::rectangle function that accepts a cv::Rect, then you will get the same result.

// just some valid rectangle arguments
int x = 0;
int y = 0;
int width = 10;
int height = 20;
// our rectangle...
cv::Rect rect(x, y, width, height);
// and its top left corner...
cv::Point pt1(x, y);
// and its bottom right corner.
cv::Point pt2(x + width, y + height);
// These two calls...
cv::rectangle(img, pt1, pt2, cv::Scalar(0, 255, 0));
// essentially do the same thing
cv::rectangle(img, rect, cv::Scalar(0, 255, 0))
like image 154
Robert Prévost Avatar answered Sep 21 '22 14:09

Robert Prévost