-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImageContourTracking
86 lines (66 loc) · 2.39 KB
/
ImageContourTracking
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace cv;
using namespace std;
/// Global variables
Mat src, src_gray;
Mat dst, detected_edges;
int edgeThresh = 1;
int lowThreshold=150;
// int const max_lowThreshold = 300;
int ratio = 3;
int kernel_size = 3;
/** @function main */
int main( int argc, char** argv )
{
/// Load an image
src = imread( argv[1] );
if( !src.data )
{ return -1; }
int start_s=clock();
/// Create a matrix of the same type and size as src (for dst)
dst.create( src.size(), src.type() );
/// Convert the image to grayscale
cvtColor( src, src_gray, CV_BGR2GRAY );
imshow( "Gray", src_gray );
/// Create a window
namedWindow( "Edge detect", CV_WINDOW_NORMAL);
namedWindow( "Canny Tracking", CV_WINDOW_NORMAL );
// CannyThreshold(0, 0);
vector<vector<Point> > contours;
/// Reduce noise with a kernel 3x3
// blur( src_gray, detected_edges, Size(3,3));
medianBlur(src_gray, detected_edges, 3);
// imshow( "window_name", detected_edges );
/// Canny detector
Canny( detected_edges, detected_edges,lowThreshold ,lowThreshold*ratio, kernel_size );
/// Using Canny's output as a mask, we display our result
dst = Scalar::all(0);
src.copyTo( dst, detected_edges);
findContours( detected_edges, contours,CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE, Point(0, 0) );
cout << "Number of Objects: " << contours.size() << std::endl;
vector<Moments> mu(contours.size() );
for( int i = 0; i < contours.size(); i++ )
{ mu[i] = moments( contours[i], false ); }
/// Get the mass centers:
vector<Point2f> mc( contours.size() );
for( int i = 0; i < contours.size(); i++ )
{ mc[i] = Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }
/// Draw contours
Mat drawing = Mat::zeros( detected_edges.size(), CV_8UC3 );
for( int i = 0; i< contours.size(); i++ )
{
circle( src, mc[i], 150, Scalar(255,0,0), 2, 8, 0 );
circle( src, mc[i], 20, Scalar(255,0,0), -1, 8, 0 );
}
imshow( "Edge detect", dst );
imshow( "Canny Tracking", src );
/// Wait until user exit program by pressing a key
waitKey(0);
int stop_s=clock();
cout << "time: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000 << endl;
return 0;
}