OpenCV有函式方便我們繪圖,這邊依序介紹如何繪製線、矩形、圓、橢圓、多角形、文字在影像上,其他圖形請參考OpenCV文件。
內文索引 [隱藏]
連通類型有兩種,不同的連通型態會影響圖案的邊界部分:
void line(Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
void rectangle(Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
void circle(Mat& img, Point center, int radius, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
void ellipse(Mat& img, Point center, Size axes, double angle, double startAngle, double endAngle, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
void polylines(Mat& img, const Point** pts, const int* npts, int ncontours, bool isClosed, const Scalar& color, int thickness=1, intlineType=8, int shift=0)
void putText(Mat& img, const string& text, Point org, int fontFace, double fontScale, Scalar color, int thickness=1, int lineType=8, bool bottomLeftOrigin=false)
以下程式碼實際繪製線、矩形、圓、橢圓、多角形、文字在影像上:
#include
#include
using namespace cv;
int main(){
Mat img(400, 400, CV_8UC3, Scalar(255,255,255));
line(img, Point(20,40), Point(120,140), Scalar(255,0,0), 3);
rectangle(img, Point(150,40), Point(250,140), Scalar(0,0,255), -1);
circle(img, Point(330,90), 50, Scalar(0,255,0), -1);
ellipse(img, Point(80,280), Size(60,40), 45, 0, 360, Scalar(255,255,0), 2);
Point points[1][5];
points[0][0] = Point(150, 270);
points[0][1] = Point(190, 220);
points[0][2] = Point(260, 255);
points[0][3] = Point(224, 296);
points[0][4] = Point(178, 316);
const Point* ppt[1] = {points[0]};
int npt[] = {5};
polylines(img, ppt, npt, 1, 1, Scalar(0,255,255),5);
putText(img, string("OpenCV"), Point(280,280), 0, 1, Scalar(0,0,0),3);
imshow("window", img);
waitKey(0);
return 0;
}