一、知識點
1、void polylines(InputOutputArray img, InputArrayOfArrays pts, bool isClosed, const Scalar & color, int thickness = 1, int lineType = LINE_8, int shift = 0 );
? (1)、在圖像上繪制多邊形曲線。
? (2)、參數說明:
? ? ? img: 輸入、輸出參數,要繪制多邊形曲線的圖像。
?? ? ?pts: 多邊形曲線的頂點數組。
?? ? ?isClosed: 標志多邊形曲線是否閉合。 若為true,則在最后一個頂點和第一個頂點之間繪制一條線段。
?? ? ?color: 多邊形曲線的顏色。
?? ? ?thickness: 多邊形曲線的粗細。
?? ? ?lineType: 線條的類型,如8連通、4連通、抗鋸齒等。
?? ? ?shift: 點坐標中的小數位數。
? (3)、注意: thickness在此函數中只能大于0,否則運行會報錯。 所以polylines()只能繪制,不能填充多邊形。
? ? ??
2、void fillPoly(InputOutputArray img, InputArrayOfArrays pts, const Scalar & color, int lineType = LINE_8, int shift = 0, Point offset = Point());
? (1)、在圖像上填充多邊形。
? (2)、參數說明:
? ? ? img: 輸入、輸出參數,要填充多邊形的圖像。
?? ? ?pts: 多邊形的頂點數組。
?? ? ?color: 多邊形填充的顏色。
?? ? ?lineType: 線條的類型,如8連通、4連通、抗鋸齒等。
?? ? ?shift: 點坐標中的小數位數。
?? ? ?offset: 輪廓所有點的可選偏移。
?? ? ?
3、void drawContours(InputOutputArray image,?
? ? ? ? ? ? ? ? ? ? InputArrayOfArrays contours,?
?? ??? ??? ??? ??? ?int contourIdx,?
?? ??? ??? ??? ??? ?const Scalar & color,
?? ??? ??? ??? ??? ?int thickness = 1,?
?? ??? ??? ??? ??? ?int lineType = LINE_8,?
?? ??? ??? ??? ??? ?InputArray hierarchy = noArray(),
?? ??? ??? ??? ??? ?int maxLevel = INT_MAX,?
?? ??? ??? ??? ??? ?Point offset = Point());
? (1)、在圖像上繪制輪廓或填充輪廓。
? (2)、參數說明:
? ? ? image: 輸入、輸出參數,要繪制或填充輪廓的圖像。
?? ? ?contours: 所有輪廓的點集數組。
?? ? ?contourIdx: 要繪制的輪廓的索引(從0開始)。 如果為負,表示繪制或填充所有的輪廓。
?? ? ?color: 要繪制或填充的輪廓的顏色。
?? ? ?thickness: >0時表示輪廓線框粗細,<0時表示填充輪廓。
?? ? ?lineType: 線條的類型,如8連通、4連通、抗鋸齒等。
?? ? ?hierarchy: 關于層次結構的可選信息。
? ? ? maxLevel: 繪制輪廓的最大級別。
?? ? ?offset: 輪廓所有點的可選偏移。
二、示例代碼
#include <iostream>
#include <opencv2/opencv.hpp>int main()
{cv::Mat canvas = cv::Mat::zeros(cv::Size(512, 512), CV_8UC3);//定義多邊形的多個頂點cv::Point p1(100, 100);cv::Point p2(350, 100);cv::Point p3(450, 280);cv::Point p4(320, 480);cv::Point p5(80, 400);//變成一個點集std::vector<cv::Point> pts;pts.push_back(p1);pts.push_back(p2);pts.push_back(p3);pts.push_back(p4);pts.push_back(p5);//繪制多邊形(只能繪制,不能填充, thickness只能>0)cv::polylines(canvas, pts, true, cv::Scalar(0, 0, 255), 4, 8, 0);//填充多邊形cv::fillPoly(canvas, pts, cv::Scalar(255, 255, 0), 8, 0);//創造兩個點集std::vector<cv::Point> pts1;pts1.push_back(cv::Point(15, 20));pts1.push_back(cv::Point(75, 20));pts1.push_back(cv::Point(65, 60));pts1.push_back(cv::Point(30, 40));std::vector<cv::Point> pts2;pts2.push_back(cv::Point(25, 25));pts2.push_back(cv::Point(100, 30));pts2.push_back(cv::Point(65, 60));pts2.push_back(cv::Point(20, 25));std::vector<std::vector<cv::Point>> vvpts;vvpts.push_back(pts1);vvpts.push_back(pts2);//用紅色線畫出兩個輪廓cv::drawContours(canvas, vvpts, -1, cv::Scalar(0, 0, 255), 4, 8);//用黃色填充第1個輪廓cv::drawContours(canvas, vvpts, 0, cv::Scalar(0, 255, 255), -1, 8);//用洋紅填充第2個輪廓cv::drawContours(canvas, vvpts, 1, cv::Scalar(255, 0, 255), -1, 8);cv::imshow("多邊形繪制", canvas);cv::waitKey(0);return 0;
}
輸出結果: