Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/Utilidades/src/ProcesamientoImagenRangosCV.cpp
blob: fe857a819ee2781e2da731471e09873126a4e77e (plain)
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/* @author Sebastián Marichal
 * 		   sebastian_marichal@hotmail.com
 * 		   sebarocker@gmail.com
 *
 * Universidad de la República, Montevideo , Uruguay
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include "highgui.h"
#include "cv.h"


// Variables para la modificacion de valores HSV
// Estos valores segmentan tonalidades verde limon
int hlower = 100; // Valores iniciales de Hue
int hupper = 141;
int SaturationMax = 255;
int Saturation = 100;
int BrightnessMax = 255;
int Brightness = 0;
int Dilate = 0;
int Erode = 0;
int Smooth = 0;
int Canny = 0;
int SmoothType = CV_BLUR;
int approxMethod = CV_CHAIN_APPROX_SIMPLE;

int maxLevelDrawCountour = 0;
int thickness = 1;
int dp = 2;
int min_radio = 5;
int max_radio = 300;

int enclosingCircle = 0;
int findCircles = 0;
// Metodos para switch controlers

void switch_enclosingCirle( int position ) {

	enclosingCircle = position;

}

void switch_findCircle( int position ) {

	findCircles = position;

}

void switch_minRadio( int position ) {

	min_radio = position;

}

void switch_maxRadio( int position ) {

	max_radio = position;

}

void switch_dp( int position ) {
	if(position<1){
		dp=position;
	}else{
		dp = position;
	}

}

void switch_maxLevelDrawCountour( int position ) {

	maxLevelDrawCountour = position;

}

void switch_thickness( int position ) {

	thickness = position;

}

void switch_canny( int position ) {

    Canny = position;

}


void switch_hlower( int position ) {

    hlower = position;

}
void switch_hupper( int position ) {

    hupper = position;

}
void switch_saturation( int position ) {

    Saturation = position;

}

void switch_saturationmax( int position ) {

    SaturationMax = position;

}

void switch_brightness( int position ) {

    Brightness = position;

}

void switch_brightnessmax( int position ) {

    BrightnessMax = position;

}

void switch_erode( int position ) {

    Erode = position;

}

void switch_dilate( int position ) {

    Dilate = position;

}

void switch_smooth( int position ) {
    Smooth = position;
}


// Metodo Principal
int main( int argc, char** argv ) {


// Declaracion de variables para manipulacion de elementos

    int height , width , step , channels , k = 1;
    int step_mono , channels_mono;

    uchar *data_hsv , *data_mono;
    bool first = true;

 // Declaramos una Variable para poder obtener una imagen del video
IplImage *frame ,  *hsv_Image , *mono_Image, *contornos;
CvScalar hsv_min;
CvScalar hsv_max;

CvMemStorage* storage = cvCreateMemStorage(0);
CvMemStorage* circleStorage = cvCreateMemStorage(0);
 // Creamos interface de Usuario ..........

   // Ventanas
   cvNamedWindow( "Imagen Fuente", 0 );
   cvResizeWindow("Imagen Fuente",550,1000);
   cvNamedWindow( "Imagen en HSV", 0 );
   cvResizeWindow("Imagen en HSV",550,1000);
   cvNamedWindow( "Img Mono", 0 );
   cvResizeWindow("Img Mono",550,800);
   cvNamedWindow( "Contornos", 0 );
   cvResizeWindow("Contornos",500,500);

   // TrackBar

   cvCreateTrackbar("Hue Upper","Imagen en HSV",&hupper,180,switch_hupper);
   cvCreateTrackbar("Hue Lower","Imagen en HSV",&hlower,180,switch_hlower);

   cvCreateTrackbar("SaturationMax","Imagen en HSV",&SaturationMax,255,switch_saturationmax);
   cvCreateTrackbar("SaturationMin","Imagen en HSV",&Saturation,255,switch_saturation);

   cvCreateTrackbar("BrightnessMax","Imagen en HSV",&BrightnessMax,255,switch_brightnessmax);
   cvCreateTrackbar("BrightnessMin","Imagen en HSV",&Brightness,255,switch_brightness);


   // Dilatacion y Erocion

    cvCreateTrackbar("Erode","Img Mono",&Erode,10,switch_erode);
    cvCreateTrackbar("Dilate","Img Mono",&Dilate,20,switch_dilate);
    cvCreateTrackbar("Smooth","Img Mono",&Smooth,1,switch_smooth);
    cvCreateTrackbar("Canny","Img Mono",&Canny,1,switch_canny);
    cvCreateTrackbar("MaxLevelDraw contour","Imagen Fuente",&maxLevelDrawCountour,20,switch_maxLevelDrawCountour);
    cvCreateTrackbar("Thickness DrawContour","Imagen Fuente",&thickness,40,switch_thickness);
    cvCreateTrackbar("Dp","Imagen Fuente",&dp,10,switch_dp);
    cvCreateTrackbar("Min Radio","Imagen Fuente",&min_radio,300,switch_minRadio);
    cvCreateTrackbar("Max Radio","Imagen Fuente",&max_radio,300,switch_maxRadio);
    cvCreateTrackbar("Enclosing Circle","Imagen Fuente",&enclosingCircle,1,switch_enclosingCirle);
    cvCreateTrackbar("Find Circle","Imagen Fuente",&findCircles,1,switch_findCircle);




// Iniciamos el Dispositivo de Captura de Video
   CvCapture* capture = cvCreateCameraCapture(0);

  // frame = cvLoadImage( "bin/azul.png", 1);
   while(1) {

      frame = cvQueryFrame( capture ); // Obtenemos Frame desde el Buffer de Video
      if( !frame ) break; // Si no Obtenemos Frame , Entonces Finalizamos el Ciclo

  // Obtenemos atributos de la  primera imagen Obtenida.
      if (first) {

        // Creamos 2 imagenes partiendo de la imagen Fuente
        hsv_Image = cvCreateImage( cvGetSize(frame), 8, 3 );
        mono_Image = cvCreateImage( cvGetSize(frame), 8, 1 );
        contornos = cvCreateImage( cvGetSize(frame), 8, 1 );

        // Obtenemos atributos de la imagen HSV
           height     = hsv_Image->height;
           width      = hsv_Image->width;
           step       = hsv_Image->widthStep/sizeof(uchar);
           channels   = hsv_Image->nChannels;

           step_mono   = mono_Image->widthStep/sizeof(uchar);
           channels_mono = mono_Image->nChannels;

           first = false;
      }

    // Convertimos imagen RGB a HSV
    cvCvtColor(frame,hsv_Image,CV_BGR2HSV);

    // Obtenemos los valores RGB de la Imagen
   data_hsv = (uchar *)hsv_Image->imageData;
   data_mono = (uchar *)mono_Image->imageData;

   hsv_min = cvScalar((double)hlower,(double)Saturation,(double)Brightness,0);
   hsv_max = cvScalar((double)(hupper +1),(double)(SaturationMax+1),(double)(BrightnessMax+1),0);
   cvInRangeS(hsv_Image,hsv_min, hsv_max,mono_Image);

// Erocionar y Dilatar , para la eliminacion de pixeles perdidos

	if(Erode>0){
		cvErode(mono_Image,mono_Image,0,Erode);
	}
	if(Dilate>0){
		cvDilate( mono_Image,mono_Image,0,Dilate);
	}
	if(Smooth>0){
		cvSmooth(mono_Image,mono_Image,SmoothType,7,7);
	}

	CvSeq* contours = NULL;
	cvCopy(mono_Image,contornos,NULL);
	if(Canny>0){
		cvCanny(mono_Image,contornos,50,200,3);
	}

	int cantContornos = cvFindContours( contornos, storage, &contours, sizeof(CvContour),CV_RETR_TREE, approxMethod, cvPoint(0,0) );
	//printf("Contornos detectados: %d\n",cantContornos);

	cvDrawContours(frame,contours,cvScalar(0,255,0,0),cvScalar(0,0,255,0),maxLevelDrawCountour,thickness,8);

	//Deteccion de circulos. Sobre la imagen contornos que es a la que se le aplica el Canny
	if(findCircles){
		CvSeq* circles =  cvHoughCircles(contornos,circleStorage,CV_HOUGH_GRADIENT,dp,100,100,300,min_radio,max_radio);
		printf("Circulos detectados: %d\n",circles->total);

		for(int i=0;i<circles->total;i++){
			float* p = (float*)cvGetSeqElem( circles, i );

			cvCircle( frame, cvPoint(cvRound(p[0]),cvRound(p[1])), 3, CV_RGB(255,0,0), -1, 8, 0 );

			cvCircle( frame, cvPoint(cvRound(p[0]),cvRound(p[1])), cvRound(p[2]), CV_RGB(200,0,0), 1, 8, 0 );

			//px[i]=cvRound(p[0]); py[i]=cvRound(p[1]);
		}
	}
	CvSeq* iter = contours;
	CvPoint2D32f centro;
	float radio;
	if(enclosingCircle){
		printf("Encontrando enclosing circles: \n");
		while(iter){
			cvMinEnclosingCircle(iter,&centro,&radio);
			cvCircle(frame,cvPoint(centro.x,centro.y),cvRound(radio),CV_RGB(255,0,0),thickness + 2,8,0 );

			printf("*** Centro : (%f,%f) , Radio : %f \n",centro.x,centro.y,radio);
			printf("*** AREA   : %f \n",pow(radio,2)*CV_PI);
			iter = iter->h_next;
		}

	}


// Desplegamos la imagenes en Ventanas

    cvShowImage( "Imagen Fuente", frame );
    cvShowImage( "Imagen en HSV", hsv_Image );
    cvShowImage( "Img Mono", mono_Image );
    cvShowImage( "Contornos", contornos );


      // Esperamos 33 milesimas de Segundo , si el usuario presiona alguna Tecla
      char c = cvWaitKey(33);
      if( c == 27 ) break; // Si se Preciono la Tecla ESC entonces se rompe el Ciclo
      if(c == 's'){ //Seleccion tipo de smooth
    	  printf("Seleccionar tipo de Smooth:\n");
    	  printf(" 1 - Blur sin escalado (CV_BLUR_NO_SCALE)\n");
    	  printf(" 2 - Blur con escalado (CV_BLUR)\n");
    	  printf(" 3 - Gaussian (CV_GAUSSIAN)\n");
    	  printf(" 4 - Mediana (CV_MEDIAN)\n");
    	  int tipo = 0;
    	  scanf("%d",&tipo); while( getchar()!='\n' );
    	  switch(tipo){
			  case 1:
				  SmoothType = CV_BLUR_NO_SCALE;
			  break;
			  case 2:
				  SmoothType = CV_BLUR;
			  break;
			  case 3:
				  SmoothType = CV_GAUSSIAN;
			  break;
			  case 4:
				  SmoothType = CV_MEDIAN;
			  break;
    	  }
		  printf("\n");
      }
      if(c=='c'){//configuracion del metodo para aproximar contornos
    	  printf("Seleccionar Metodo para extraer contornos:\n");
		  printf(" 1 - CV_CHAIN_CODE (Freeman chain code)\n");
		  printf(" 2 - CV_CHAIN_APROX_NONE (No aproxima)\n");
		  printf(" 3 - CV_CHAIN_APPROX_SIMPLE (Comprime lineas horiz, vert y diag. Deja solo puntos finales)\n");
		  printf(" 4 - CV_CHAIN_APPROX_TC89_L1 (Algoritmo de aproximacion de Teh-Chin)\n");
		  printf(" 5 - CV_CHAIN_APPROX_TC89_KCOS (Otro Algoritmo de aproximacion de Teh-Chin)\n");
		  printf(" 6 - CV_LINK_RUNS (Une segmentos horizontals de unos. Solo se puede usar con CV_RETR_LIST)\n");
		  int tipo=0;
		  scanf("%d",&tipo); while( getchar()!='\n' );
		  switch(tipo){
			  case 1:
				  approxMethod= CV_CHAIN_CODE;
			  break;
			  case 2:
				  approxMethod= CV_CHAIN_APPROX_NONE;
			  break;
			  case 3:
				  approxMethod= CV_CHAIN_APPROX_SIMPLE;
			  break;
			  case 4:
				  approxMethod = CV_CHAIN_APPROX_TC89_L1;
			  break;
			  case 5:
				  approxMethod = CV_CHAIN_APPROX_TC89_KCOS;
			  break;
			  case 6:
				  approxMethod = CV_LINK_RUNS;
			  break;
		  }
		  printf("\n");
      }
   }

   // Liberamos Variables en Memoria
   cvReleaseImage(&frame);
   cvReleaseImage(&hsv_Image);
   cvReleaseImage(&mono_Image);
   cvReleaseImage(&contornos);

   cvReleaseMemStorage(&storage);
   cvReleaseMemStorage(&circleStorage);

   cvReleaseCapture(&capture );
	cvDestroyWindow( "Imagen Fuente" );
	cvDestroyWindow( "Imagen en HSV" );
	cvDestroyWindow( "Img Mono" );
	cvDestroyWindow( "Contornos" );
} // fin del metodo principal





















/*******	EN VEZ DEL CVRANGES SE PUEDE USAR EL SIGUIENTE CODIGO***************************/
// Recorremos la imagen
   /*   for(int i = 0; i <height; i++ ) {
          for(int j = 0; j <width; j++ ) {

        // Segmentamos la imagen mediante los angulos de Hue
            if (((data_hsv[i*step+j*channels])>= hlower) && ((data_hsv[i*step+j*channels]) <= hupper)){
                if(data_hsv[i*step+j*channels]>180){
					printf("Mayor a 180\n");
				}
                if(filtrarPorSaturacion){
					if (data_hsv[i*step+j*channels+1]>= Saturation && data_hsv[i*step+j*channels+1]<=SaturationMax) {
						if(filtrarPorBrillo){
							if (data_hsv[i*step+j*channels+2]>= Brightness && data_hsv[i*step+j*channels+2]<= BrightnessMax) {
								// Coloreamos el pixel en blanco
								data_mono[i*step_mono+j*channels_mono] = 255;
							}else{
								// Coloreamos el pixel en negro
								data_mono[i*step_mono+j*channels_mono] = 0;
							}
						}else{
							// Coloreamos el pixel en blanco
							data_mono[i*step_mono+j*channels_mono] = 255;
						}
					}
					else{
						// Coloreamos el pixel en negro
						data_mono[i*step_mono+j*channels_mono] = 0;
					}
				}else if(filtrarPorBrillo){
					if (data_hsv[i*step+j*channels+2]>= Brightness) {
						// Coloreamos el pixel en blanco
						data_mono[i*step_mono+j*channels_mono] = 255;
					}else{
						// Coloreamos el pixel en negro
						data_mono[i*step_mono+j*channels_mono] = 0;
					}
				}else{
					// Coloreamos el pixel en blanco
					data_mono[i*step_mono+j*channels_mono] = 255;
				}
            } else {
                // Coloreamos el pixel en negro
                data_mono[i*step_mono+j*channels_mono] = 0;
            }

        } // fin del for j
      } // fin del for i
*/