【計算機視覺】OpenCV篇(9) - 輪廓(尋找/繪制輪廓)
阿新 • • 發佈:2019-05-14
app oop blank parser gin 邊緣檢測 alt win orm
什麽是輪廓?
輪廓是一系列相連的點組成的曲線,代表了物體的基本外形。
輪廓與邊緣好像挺像的?
是的,確實挺像,那麽區別是什麽呢?簡而言之,輪廓是連續的,而邊緣並不全都連續(見下圖示例)。其實邊緣主要是作為圖像的特征使用,比如可以用邊緣特征可以區分臉和手,而輪廓主要用來分析物體的形態,比如物體的周長和面積等,可以說邊緣包括輪廓。
邊緣和輪廓的區別(圖片來源:http://pic.ex2tron.top/cv2_understand_contours.jpg)
尋找輪廓的操作一般用於二值化圖,所以通常會使用閾值分割或Canny邊緣檢測先得到二值圖。
【註:尋找輪廓是針對白色物體的,一定要保證物體是白色,而背景是黑色,不然很多人在尋找輪廓時會找到圖片最外面的一個框】
OpenCV4.1.0 C++ Sample Code:
/** * @function findContours_Demo.cpp * @brief Demo code to find contours in an image * @author OpenCV team */ #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include <iostream> using namespace cv; using namespace std; Mat src_gray; int thresh = 100; RNG rng(12345); /// Function header void thresh_callback(int, void* ); /** * @function main */ int main( int argc, char** argv ) { /// Load source image CommandLineParser parser( argc, argv, "{@input | ../data/HappyFish.jpg | input image}" ); Mat src = imread( parser.get<String>( "@input" ) ); if( src.empty() ) { cout << "Could not open or find the image!\n" << endl; cout << "Usage: " << argv[0] << " <Input image>" << endl; return -1; } /// Convert image to gray and blur it cvtColor( src, src_gray, COLOR_BGR2GRAY ); blur( src_gray, src_gray, Size(3,3) ); /// Create Window const char* source_window = "Source"; namedWindow( source_window ); imshow( source_window, src ); const int max_thresh = 255; createTrackbar( "Canny thresh:", source_window, &thresh, max_thresh, thresh_callback ); thresh_callback( 0, 0 ); waitKey(); return 0; } /** * @function thresh_callback */ void thresh_callback(int, void* ) { /// Detect edges using Canny Mat canny_output; Canny( src_gray, canny_output, thresh, thresh*2 ); /// Find contours vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours( canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE ); /// Draw contours Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 ); for( size_t i = 0; i< contours.size(); i++ ) { Scalar color = Scalar( rng.uniform(0, 256), rng.uniform(0,256), rng.uniform(0,256) ); drawContours( drawing, contours, (int)i, color, 2, LINE_8, hierarchy, 0 ); } /// Show in a window imshow( "Contours", drawing ); }
Result:
【計算機視覺】OpenCV篇(9) - 輪廓(尋找/繪制輪廓)