一般一個輪廓都對應一系列的點,也就是圖像中的一條曲線。其表示方法可能根據不同的情況有所不同。
可以利用 findContours()函數從二值圖像中查找輪廓。
CV_EXPORTS_W void findContours( InputArray image, OutputArrayOfArrays contours,
OutputArray hierarchy, int mode,
int method, Point offset = Point());
第一個參數,輸入圖像,需爲8位單通道圖像。
第二個參數 ,檢測到的輪廓,函數調用後的運算結果存在這裏
每個輪廓存儲爲一個點向量 ,即用point類型的vector表示
第三個參數爲可選擇的輸出參數,包含圖像的拓撲信息。每個輪廓contours[i]對應四個hierarchy元素
hierarchy[i][0]~hierarchy[i][3],分別表示後一個輪廓,前一個輪廓,父輪廓,內嵌輪廓的索引編號。
如果沒有對應值,對應的hierarchy[i]設置爲負值
第四個參數 mode,輪廓索引方式
/** retrieves only the extreme outer contours. It sets `hierarchy[i][2]=hierarchy[i][3]=-1` for
all the contours. */
RETR_EXTERNAL = 0,
/** retrieves all of the contours without establishing any hierarchical relationships. */
RETR_LIST = 1,
/** retrieves all of the contours and organizes them into a two-level hierarchy. At the top
level, there are external boundaries of the components. At the second level, there are
boundaries of the holes. If there is another contour inside a hole of a connected component, it
is still put at the top level. */
RETR_CCOMP = 2,
/** retrieves all of the contours and reconstructs a full hierarchy of nested contours.*/
RETR_TREE = 3,
第五個參數 method爲輪廓的近似辦法
/** stores absolutely all the contour points. That is, any 2 subsequent points (x1,y1) and
(x2,y2) of the contour will be either horizontal, vertical or diagonal neighbors, that is,
max(abs(x1-x2),abs(y2-y1))==1. */
CHAIN_APPROX_NONE = 1,
/** compresses horizontal, vertical, and diagonal segments and leaves only their end points.
For example, an up-right rectangular contour is encoded with 4 points. */
CHAIN_APPROX_SIMPLE = 2,
/** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */
CHAIN_APPROX_TC89_L1 = 3,
/** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */
CHAIN_APPROX_TC89_KCOS = 4
第六個參數 Point類型的offset ,每個輪廓點的可選偏移量,有默認值point()。對ROI圖像中找出的輪廓,並要在整個圖像中進行分析時,這個參數就排上用場了。
findContours經常與drawContours配合使用,檢測到輪廓後使用drawContours繪製出來。
CV_EXPORTS_W 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() );
threshold(GrayImg, GrayImg, 125, 255, 0);
imshow("input img", GrayImg);
Mat dstImg;
dstImg = Mat::zeros(Img1.size(), Img1.type());
vector<vector<Point>> contours; //存放輪廓的點
vector<Vec4i> hierachy;
findContours(GrayImg, contours, hierachy, RETR_CCOMP, CHAIN_APPROX_SIMPLE);
int index = 0;
for (;index >= 0; index = hierachy[index][0])
{
Scalar color(rand() % 255, rand() % 255, rand() % 255);
drawContours(dstImg, contours,index, color, FILLED, LINE_AA, hierachy);
}
imshow("Output Img", dstImg);