1 | #include "opencv2/imgproc/imgproc.hpp"
|
2 | #include "opencv2/highgui/highgui.hpp"
|
3 | #include <fstream>
|
4 | using std::ifstream;
|
5 | using std::ofstream;
|
6 | #include <iostream>
|
7 | using std::cerr;
|
8 | using std::cout;
|
9 | using std::endl;
|
10 | #include <dirent.h>
|
11 | #include <cstdlib>
|
12 | #include <stdio.h>
|
13 | #include <ctype.h>
|
14 | #include <stdlib.h>
|
15 | #include <string>
|
16 | using namespace std;
|
17 | using namespace cv;
|
18 |
|
19 | Mat contour(Mat image);
|
20 |
|
21 | int main( int argc, const char** argv )
|
22 | {
|
23 | Mat image = imread( argv[1], 1 );
|
24 | Mat new_image = contour(image);
|
25 | imshow("Output", new_image);
|
26 | waitKey();
|
27 | return 0;
|
28 | }
|
29 |
|
30 | Mat contour(Mat image)
|
31 | {
|
32 | cvtColor(image,image,CV_BGR2GRAY);
|
33 |
|
34 | int threshval = 40;
|
35 | int max_thresh = 255;
|
36 | RNG rng(12345);
|
37 |
|
38 | Mat threshold_output;
|
39 | vector<vector<Point> > contours;
|
40 | vector<Vec4i> hierarchy;
|
41 |
|
42 | threshold( image, threshold_output, threshval, 255, THRESH_BINARY );
|
43 |
|
44 | findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
|
45 |
|
46 | Mat cimage = Mat::zeros(image.size(), CV_8UC3);
|
47 |
|
48 | for(size_t i = 0; i < contours.size(); i++)
|
49 | {
|
50 | size_t count = contours[i].size();
|
51 | if( count < 6 )
|
52 | continue;
|
53 |
|
54 | Mat pointsf;
|
55 | Mat(contours[i]).convertTo(pointsf, CV_32F);
|
56 | RotatedRect box = fitEllipse(pointsf);
|
57 | cout << "width: " << box.size.width << " height: " << box.size.height << endl;
|
58 | if( MAX(box.size.width, box.size.height) > MIN(box.size.width, box.size.height)*30 )
|
59 | continue;
|
60 | drawContours(cimage, contours, (int)i, Scalar::all(255), 1, 8, vector<Vec4i>(), 0, Point());
|
61 |
|
62 |
|
63 | vector<Point> hullPoints;
|
64 | vector<Point> convexityDefects;
|
65 |
|
66 | convexHull(contours[i], hullPoints, true, true);
|
67 | convexityDefects(contours[i], hullPoints, convexityDefects);
|
68 |
|
69 | int hullcount = (int)hullPoints.size();
|
70 | for( int j = 1; j < hullcount; j++ )
|
71 | {
|
72 | line(cimage, hullPoints[j-1], hullPoints[j], Scalar(0, 255, 0), 1, CV_AA);
|
73 | circle(cimage, hullPoints[j], 1, Scalar(0, 0, 255), CV_FILLED, CV_AA);
|
74 | }
|
75 | }
|
76 | return cimage;
|
77 | }
|