1 #include <opencv2/opencv.hpp> 2 #include <iostream> 3 4 using namespace cv; 5 using namespace std; 6 7 8 int main(int argc, char** argv) 9 { 10 Mat src = imread("test.jpg"); 11 Mat src_gray,binary,dst=Mat::zeros(src.size(),CV_8UC3); 12 if (src.empty()) { 13 printf("Could not load image..."); 14 return -1; 15 } 16 imshow("Input Image",src); 17 18 //二值化 19 cvtColor(src, src_gray, COLOR_BGR2GRAY); 20 threshold(src_gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU); 21 //binary = ~binary;//取反 22 imshow("binary", binary); 23 24 //发现轮廓 25 vector<vector<Point>> contours; 26 vector<Vec4i> hireachy; 27 findContours(binary, contours, hireachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point()); 28 29 //绘制所有轮廓 30 for (size_t t = 0; t < contours.size(); t++) 31 { 32 drawContours(dst, contours, t, Scalar(0, 0, 255), 2, 8, Mat(), 0, Point());//dst必须先初始化 33 } 34 35 imshow("contours", dst); 36 37 waitKey(0); 38 39 return 0; 40 }