Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/CenterofBlob/center_of_multipe_blob.cpp
3118 views
1
#include "opencv2/highgui/highgui.hpp"
2
#include "opencv2/imgproc/imgproc.hpp"
3
#include <iostream>
4
#include <stdio.h>
5
#include <stdlib.h>
6
7
using namespace cv;
8
using namespace std;
9
10
RNG rng(12345);
11
12
void find_moments( Mat src );
13
14
int main(int argc, char** argv)
15
{
16
/// Load source image, convert it to gray
17
Mat src, gray;
18
src = imread(argv[1], 1 );
19
20
cvtColor( src, gray, COLOR_BGR2GRAY );
21
22
namedWindow( "Source", WINDOW_AUTOSIZE );
23
imshow( "Source", src );
24
// call function to find_moments
25
find_moments( gray );
26
27
waitKey(0);
28
return(0);
29
}
30
31
void find_moments( Mat gray )
32
{
33
Mat canny_output;
34
vector<vector<Point> > contours;
35
vector<Vec4i> hierarchy;
36
37
/// Detect edges using canny
38
Canny( gray, canny_output, 50, 150, 3 );
39
// Find contours
40
findContours( canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0) );
41
42
/// Get the moments
43
vector<Moments> mu(contours.size() );
44
for( int i = 0; i < contours.size(); i++ )
45
{ mu[i] = moments( contours[i], false ); }
46
47
/// Get the centroid of figures.
48
vector<Point2f> mc( contours.size() );
49
for( int i = 0; i < contours.size(); i++ )
50
{ mc[i] = Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }
51
52
53
/// Draw contours
54
55
Mat drawing(canny_output.size(), CV_8UC3, Scalar(255,255,255));
56
57
for( int i = 0; i< contours.size(); i++ )
58
{
59
Scalar color = Scalar(167,151,0);
60
drawContours( drawing, contours, i, color, 2, 8, hierarchy, 0, Point() );
61
circle( drawing, mc[i], 4, color, -1, 7, 0 );
62
}
63
64
/// Show the resultant image
65
namedWindow( "Contours", WINDOW_AUTOSIZE );
66
imshow( "Contours", drawing );
67
waitKey(0);
68
69
}
70
71