1 #include <opencv2/opencv.hpp> 2 #include <iostream> 3 #include <math.h> 4 5 using namespace cv; 6 using namespace std; 7 8 int main(int argc, char** argv) { 9 Mat src = imread("test.jpg"); 10 if (src.empty()) { 11 printf("could not load image... "); 12 return -1; 13 } 14 namedWindow("input image", CV_WINDOW_AUTOSIZE); 15 imshow("input image", src); 16 17 //高斯降噪 18 Mat blurImage; 19 GaussianBlur(src, blurImage, Size(15, 15), 0, 0); 20 imshow("blur", blurImage); 21 22 Mat gray_src, binary; 23 cvtColor(blurImage, gray_src, COLOR_BGR2GRAY); 24 threshold(gray_src, binary, 0, 255, THRESH_BINARY | THRESH_TRIANGLE);//颜色单一的图像使用THRESH_TRIANGLE 25 imshow("binary", binary); 26 27 // 形态学闭操作,去掉空洞 28 Mat morphImage; 29 Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1)); 30 morphologyEx(binary, morphImage, MORPH_CLOSE, kernel, Point(-1, -1), 2); 31 imshow("morphology", morphImage); 32 33 // 获取最大轮廓 34 vector<vector<Point>> contours; 35 vector<Vec4i> hireachy; 36 findContours(morphImage, contours, hireachy, CV_RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point()); 37 Mat connImage = Mat::zeros(src.size(), CV_8UC3); 38 for (size_t t = 0; t < contours.size(); t++) { 39 Rect rect = boundingRect(contours[t]); 40 if (rect.width < src.cols / 2) continue;//轮廓筛选 41 if (rect.width > (src.cols - 20)) continue;//轮廓筛选 42 double area = contourArea(contours[t]); 43 double len = arcLength(contours[t], true); 44 drawContours(connImage, contours, static_cast<int>(t), Scalar(0, 0, 255), 1, 8, hireachy); 45 printf("area of star could : %f ", area); 46 printf("length of star could : %f ", len); 47 } 48 imshow("result", connImage); 49 50 waitKey(0); 51 return 0; 52 }