标签:bsp source The target imshow NPU app enter command
什么是轮廓?
轮廓是一系列相连的点组成的曲线,代表了物体的基本外形。
轮廓与边缘好像挺像的?
是的,确实挺像,那么区别是什么呢?简而言之,轮廓是连续的,而边缘并不全都连续(见下图示例)。其实边缘主要是作为图像的特征使用,比如可以用边缘特征可以区分脸和手,而轮廓主要用来分析物体的形态,比如物体的周长和面积等,可以说边缘包括轮廓。
边缘和轮廓的区别(图片来源: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) - 轮廓(寻找/绘制轮廓)
标签:bsp source The target imshow NPU app enter command
原文地址:https://www.cnblogs.com/carsonzhu/p/10863870.html