1. 程式人生 > >(10)繪製形狀和文字

(10)繪製形狀和文字

基本程式碼,這個我自己沒有實驗

 1 #include "../common/common.hpp"
 2 
 3     static Mat bgImage;
 4     static void drawLines();
 5     static void drawRectangle();
 6     static void drawEllipse();
 7     static void drawCircle();
 8     static void drawPolygon();
 9     static void drawRandomLine();
10 
11     void
main1_8(int argc, char** argv) 12 { 13 bgImage = imread(getCVImagesPath("images/test1.png"), IMREAD_COLOR); 14 drawLines(); 15 drawRectangle(); 16 drawEllipse(); 17 drawCircle(); 18 drawPolygon(); 19 //引數:Mat,文字(不識別中文?),文字的位置(錨點?),字型,縮放,顏色,線寬,線型別
20 putText(bgImage, "Hello OpenCV", Point(0, 200), CV_FONT_HERSHEY_COMPLEX, 1.0, Scalar(0), 3, LINE_8);//繪製文字 21 imshow("src", bgImage); 22 23 drawRandomLine(); 24 25 waitKey(0); 26 } 27 28 void drawLines()//繪製線條 29 { 30 Point p1 = Point(20, 30);//Point表示平面上的點,OpenCV中的這些座標值都是相對於影象本身畫素值的
31 Point p2; 32 p2.x = 400; 33 p2.y = 400; 34 Scalar color = Scalar(0, 0, 255); 35 line(bgImage, p1, p2, color, 10, LINE_AA);//繪製線條到Mat,10是線寬、LINE_4或LINE_8是帶鋸齒的,LINE_AA是抗鋸齒的 36 } 37 38 void drawRectangle()//繪製矩形 39 { 40 //OpenCV的座標系,原點在螢幕左上角,x朝右正,y朝下正 41 Rect rect = Rect(200, 100, 300, 300);//起始位置x、y,寬,高 42 Scalar color = Scalar(255, 0, 0); 43 rectangle(bgImage, rect, color, LINE_8);//繪製矩形到Mat,自帶圓角。。 44 } 45 46 void drawEllipse()//繪製橢圓 47 { 48 int width = bgImage.cols; 49 int height = bgImage.rows; 50 Scalar color = Scalar(0, 255, 0); 51 //繪製橢圓,引數:Mat,中心點,橢圓的長短軸半徑,橢圓的朝向(0表示水平),起始角度,終點角度 52 ellipse(bgImage, Point(width / 2, height / 2), Size(width / 4, height / 8), 0, 0, 270, color, 2, LINE_8); 53 } 54 55 void drawCircle()//繪製圓 56 { 57 Scalar color = Scalar(0, 255, 255); 58 circle(bgImage, Point(bgImage.cols / 2, bgImage.rows / 2), 150, color, 2, LINE_8); 59 } 60 61 void drawPolygon()//繪製多邊形,繪製的多邊形是填充的 62 { 63 Point pts[1][5]; 64 pts[0][0] = Point(100, 100); 65 pts[0][1] = Point(100, 200); 66 pts[0][2] = Point(200, 200); 67 pts[0][3] = Point(200, 100); 68 pts[0][4] = Point(100, 100); 69 70 const Point * ppts[] = { pts[0] }; 71 int npt[] = { 5 }; 72 Scalar color = Scalar(255, 0, 255); 73 //引數:Mat,頂點資料指標,頂點個數,1表示只繪製一個contour(輪廓) 74 fillPoly(bgImage, ppts, npt, 1, color, LINE_8); 75 } 76 77 void drawRandomLine()//迴圈繪製隨機位置隨機顏色的線段 78 { 79 Mat randomLineMat = Mat::zeros(bgImage.size(), bgImage.type()); 80 RNG rng(12345);//生成高斯隨機數,引數種子 81 Point p1, p2; 82 for (int i = 0; i < 100000; i++) 83 { 84 p1.x = rng.uniform(0, randomLineMat.cols);//生成正態分佈 0-bgImage.cols 範圍內的隨機數 85 p1.y = rng.uniform(0, randomLineMat.rows); 86 p2.x = rng.uniform(0, randomLineMat.cols); 87 p2.y = rng.uniform(0, randomLineMat.rows); 88 Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); 89 if (waitKey(50) > 0)//引數delay如果傳0表示阻塞等待鍵盤事件,傳大於0表示只阻塞等待delay毫秒,鍵盤無響應返回-1 90 { 91 break; 92 } 93 line(randomLineMat, p1, p2, color, 1, LINE_8); 94 imshow("randomLine", randomLineMat); 95 } 96 }