1.輪廓發現(find contour in your image)
- 輪廓發現(find contour)
- 代碼演示
2.介紹
輪廓發現是基於圖像邊緣提取的基礎尋找對象輪廓的方法,所以邊緣提取的閾值選定會影響最終輪廓發現結果
3.API介紹
- 在二值圖像上發現輪廓使用API
cv::findContours(
InputOutputArray binImg, // 輸入圖像,非0的像素被看成1,0的像素值保持不變,8-bit
OutputArrayOfArrays contours,// 全部發現的輪廓對象
OutputArray, hierachy// 圖該的拓撲結構,可選,該輪廓發現算法正是基於圖像拓撲結構實現。
int mode, // 輪廓返回的模式,一般返回一個輪廓樹
int method,// 發現方法
Point offset=Point()// 輪廓像素的位移,默認(0, 0)沒有位移
)
- cv::findContours之後對發現的輪廓數據進行繪製顯示
drawContours(
InputOutputArray binImg, // 輸出圖像
OutputArrayOfArrays contours,// 全部發現的輪廓對象
Int contourIdx// 輪廓索引號
const Scalar & color,// 繪製時候顏色
int thickness,// 繪製線寬
int lineType ,// 線的類型LINE_8
InputArray hierarchy,// 拓撲結構圖
int maxlevel,// 最大層數, 0只繪製當前的,1表示繪製繪製當前及其內嵌的輪廓
Point offset=Point()// 輪廓位移,可選
)
4.演示代碼
大致步驟:
1.輸入圖像轉爲灰度圖像cvtColor
2.使用Canny進行邊緣提取,得到二值圖像
3.使用findContours尋找輪廓
4.使用drawContours繪製輪廓
void Demo_Contours(int,void*){
vector<vector<Point>>contours;
vector<Vec4i>hierarchy;
Canny(src,dst,threshold_value,threshold_value*2,3,false);
findContours(dst,contours,hierarchy,RETR_TREE,CHAIN_APPROX_SIMOPLE,POint(0,0));
Mat drawImg = Mat::zeros(dst,size(),CV_8UC3);
for(size_t i = 0;i < contours.size();i++){
Scalar color = Scalar (rng.uniform(0,255),rng.uniform(0,255),rng.uniform(0,255))
drawContours(drawImg,contours,i,color,2,LINE_8,hierarchy,0,Point(0,0));
}
imshow(output_win,drawImg);
}
做項目時:一定要使用數組,不要用vector,速度會很慢
5.舉例
6.課外擴展
圖像的拓撲結構
findContours()函數
drawContours()函數
opencv中vector_ vector Point,vector_vec4i_,vector_Rect_,vector_RotatedRect_含義