【练习8.5】轮廓长度计算机cvApproxPoly逼近
题目要求 | 程序代码 | 结果图片 | 要言妙道 | 借鉴参考 |
a、检测轮廓并计算轮廓长度
b、分别使用1/90,1/66,1/11,1/10做为精度参数,使用cvApproxPoly逼近,计算轮廓长度并画出结果
1 // OpenCVExerciseTesting.cpp : 定义控制台应用程序的入口点。 2 // 3 // string file_full_name = "D:\\Work\\Work_Programming\\Source\\Image\\OpenCVExerciseImage\\第8章\\r20.jpg"; 4 5 6 #include "stdafx.h" 7 #include<string> 8 #include <cv.h> 9 #include <highgui.h> 10 #include <iostream> 11 #include<math.h> 12 13 #include <opencv2/legacy/legacy.hpp> 14 //#pragma comment(lib, "opencv_legacy2411.lib") 15 16 using namespace cv; 17 using namespace std; 18 19 //函数声明-->--->-->--->-->--->-->--->// 20 21 22 //<--<--<--<--<--<--<--<--<--函数声明// 23 24 int _tmain(int argc, _TCHAR* argv[]) 25 { 26 string file_full_name = "D:\\Work\\Work_Programming\\Source\\Image\\OpenCVExerciseImage\\第8章\\r20.jpg"; 27 28 IplImage * image_source = cvLoadImage(file_full_name.c_str(), CV_LOAD_IMAGE_GRAYSCALE); 29 CV_Assert(image_source); 30 31 IplImage * image_binary = cvCloneImage(image_source); 32 cvZero(image_binary); 33 34 cvThreshold(image_source, image_binary, 125, 255, CV_THRESH_BINARY); 35 36 CvMemStorage *storage = cvCreateMemStorage(); 37 CvSeq* first_contour=NULL; 38 int contour_num; 39 contour_num = cvFindContours(image_binary, storage, &first_contour, sizeof(CvContour), CV_RETR_LIST); 40 41 cout << "轮廓数" << contour_num << endl; 42 43 double contour_length; 44 //for (CvSeq * c = first_contour; c != NULL; c = c->h_next) 45 //{ 46 // contour_length = cvContourPerimeter(c); 47 // cout << "周长" << contour_length << endl; 48 //} 49 contour_length = cvContourPerimeter(first_contour); 50 cout << "周长" << contour_length << endl; 51 52 double perimeter = 126.7; 53 double parameters[4] = { 126.7 / 90, 126.7 / 66, 126.7 / 11, 126.7 / 10 }; 54 CvMemStorage* storage_approx = cvCreateMemStorage(); 55 56 IplImage *image_approx = cvCloneImage(image_binary); 57 cvZero(image_approx); 58 CvSeq *seq_approx=NULL; 59 60 string window_name = "Approx窗口";; 61 for (int i = 0; i < 4; ++i) 62 { 63 seq_approx = cvApproxPoly(first_contour, sizeof(CvContour), storage_approx, CV_POLY_APPROX_DP, parameters[i], 0); 64 contour_length = cvContourPerimeter(seq_approx); 65 cout << contour_length << endl; 66 window_name = window_name + "."; 67 cvDrawContours(image_approx, seq_approx, cvScalar(255), cvScalar(125), 0); 68 cvShowImage(window_name.c_str(), image_approx); 69 } 70 71 cvWaitKey(0); 72 73 cvReleaseImage(&image_source); 74 cvReleaseImage(&image_binary); 75 cvReleaseImage(&image_approx); 76 cvDestroyAllWindows(); 77 78 return 0; 79 }
‖==========钟于原创 乐于分享 宁静致远 毋忆典藏==========‖