1
+ #include < iostream>
2
+ #include < string>
3
+ #include < vector>
4
+
5
+ #include < opencv2/highgui/highgui.hpp>
6
+ #include < opencv2/imgproc/imgproc.hpp>
7
+
8
+ using namespace cv ;
9
+ using namespace std ;
10
+
11
+ int main ()
12
+ {
13
+ Mat img, hsv, binary;
14
+
15
+ VideoCapture cap (0 );
16
+
17
+ // verificar si se ha podido acceder a la web cam
18
+ if (!cap.isOpened ()) {
19
+ cout << " Error al acceder a la web cam." << endl;
20
+ system (" pause" );
21
+ return -1 ;
22
+ }
23
+
24
+ while (true )
25
+ {
26
+ // obtener frame de la web cam
27
+ cap >> img;
28
+
29
+ // convertir imagen RGB a HSV
30
+ cvtColor (img, hsv, CV_BGR2HSV);
31
+
32
+ // aplicar filtro para color deseado
33
+ inRange (hsv, Scalar (110 , 50 , 50 ), Scalar (130 , 255 , 255 ), binary);
34
+
35
+ // aplicar tranformaciones morfologicas (extrae la region de interes)
36
+ Mat element = getStructuringElement (MORPH_RECT, Size (15 , 15 ));
37
+ erode (binary, binary, element);
38
+ dilate (binary, binary, element);
39
+
40
+ // buscar contornos en la imagen binaria
41
+ vector< vector<Point > > contours;
42
+ findContours (binary, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
43
+
44
+ // dibujar todos los contornos encontrados
45
+ drawContours (binary, contours, -1 , Scalar (255 ), CV_FILLED);
46
+
47
+ // dibujar rectangulo y texto con coordenadas (x, y)
48
+ for (vector<Point > contour : contours) {
49
+ // dibujar rectangulo
50
+ Rect r = boundingRect (contour);
51
+ rectangle (img, r, CV_RGB (255 , 0 , 0 ), 2 , CV_AA, 0 );
52
+
53
+ Point center (r.x + (r.width / 2 ), r.y + (r.height / 2 ));
54
+
55
+ ostringstream str;
56
+ str << center.x << " ," << center.y ;
57
+
58
+ // mostrar texto (x, y)
59
+ putText (img, str.str (), center, FONT_HERSHEY_COMPLEX_SMALL, 0.60 , CV_RGB (0 , 255 , 0 ), 1 , CV_AA);
60
+ }
61
+
62
+ imshow (" Track Color" , img);
63
+ imshow (" Track Color - Binary" , binary);
64
+
65
+ // terminar la aplicacion con la tecla ESC
66
+ if (waitKey (30 ) == 27 ) break ;
67
+
68
+ }
69
+
70
+ return 0 ;
71
+ }
0 commit comments