C++ 在 OpenCV 中绘制矩形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40120433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Draw rectangle in OpenCV
提问by Adel Khatem
I want to draw a rectangle in OpenCV by using this function:
我想使用这个函数在 OpenCV 中绘制一个矩形:
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?
这个函数我理解,但是第一个函数我在参数中遇到了问题Rect
。我不知道我怎么能更致命?
回答by Robert Prévost
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.
cv::rectangle
接受 two的函数cv::Point
采用矩形的左上角和右下角(文档中分别为 pt1 和 pt2 )。如果该矩形与cv::rectangle
接受 a的函数一起使用cv::Rect
,那么您将获得相同的结果。
// 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))
回答by Saransh Kejriwal
Here's a simple example of drawing a pre-defined rectangle on an image
这是在图像上绘制预定义矩形的简单示例
using namespace cv;
int main(){
Mat img=imread("myImage.jpg");
Rect r=Rect(10,20,40,60);
//create a Rect with top-left vertex at (10,20), of width 40 and height 60 pixels.
rectangle(img,r,Scalar(255,0,0),1,8,0);
//draw the rect defined by r with line thickness 1 and Blue color
imwrite("myImageWithRect.jpg",img);
return 0;
}