Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/multi/SRC/detectorCuadrados.cpp
blob: eeac4ad2e88829f3f46db34e2bc8f2d30603b7db (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
#ifdef _CH_
#pragma package <opencv>
#endif

#define CV_NO_BACKWARD_COMPATIBILITY

#include "cv.h"
#include "highgui.h"
#include <stdio.h>
#include <math.h>
#include <string.h>

#define MIN_AREA 400

//Valores de tonalidad correspondiente al color que se quiere detectar
int hlower = 113;
int hupper = 126;
int thresh1 = 50;




// helper function:
// finds a cosine of angle between vectors
// from pt0->pt1 and from pt0->pt2
double angle( CvPoint* pt1, CvPoint* pt2, CvPoint* pt0 )
{
    double dx1 = pt1->x - pt0->x;
    double dy1 = pt1->y - pt0->y;
    double dx2 = pt2->x - pt0->x;
    double dy2 = pt2->y - pt0->y;
    return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}





void segmentarImagen(IplImage* img,IplImage* mono_Image, int hlower,int hupper,int mostrarImagen){
	uchar *data_hsv , *data_mono;
	
	IplImage* hsv_Image = cvCreateImage( cvGetSize(img), 8, 3 );
    
    
    // Obtenemos atributos de la imagen HSV
	int height     = hsv_Image->height;
	int width      = hsv_Image->width;
	int step       = hsv_Image->widthStep/sizeof(uchar);
	int channels   = hsv_Image->nChannels;

	int step_mono   = mono_Image->widthStep/sizeof(uchar);
	int channels_mono = mono_Image->nChannels;
	
	/* DEBUG DE LA IMAGEN HSV*/
	/*printf("Datos de la imagen HSV\n");
	printf("height = %d\n",height);
	printf("width = %d\n",width);
	printf("step = %d\n",step);
	printf("channels = %d\n",channels);*/
	
	/* DEBUG DE LA IMAGEN MONO */
	/*printf("Datos de la imagen MONO\n");
	printf("step = %d\n",step_mono);
	printf("channels = %d\n",channels_mono);*/
	
	
	// Convertimos imagen RGB a HSV
    cvCvtColor(img,hsv_Image,CV_RGB2HSV);
    
    // Obtenemos los valores RGB de la Imagen
   data_hsv = (uchar *)hsv_Image->imageData;
   data_mono = (uchar *)mono_Image->imageData;
   
   // 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)){
							/*	DESCOMENTAR EL SIGUIENTE CODIGO PARA FILTRAR PRO SATURACION Y BRILLO */
							 // if (data_hsv[i*step+j*channels+1]>= Saturation) {
							//		if (data_hsv[i*step+j*channels+2]>= Brightness) {
									// Coloreamos el pixel en negro
							//		 data_mono[i*step_mono+j*channels_mono] = 255;
							//		} else {     
									// Coloreamos el pixel en blanco
							//		  data_mono[i*step_mono+j*channels_mono] = 0;
							//		}
							//	} else {     
								// Coloreamos el pixel en blanco
							//	  data_mono[i*step_mono+j*channels_mono] = 0;
							//	}
							data_mono[i*step_mono+j*channels_mono] = 255;
				//printf("negro\n");
            } else {
                // Coloreamos el pixel en blanco
                //printf("blanco\n");
                data_mono[i*step_mono+j*channels_mono] = 0;
            }
        } // fin del for j
      } // fin del for i
 

      if(mostrarImagen){
		cvNamedWindow( "Imagen en HSV", CV_WINDOW_AUTOSIZE );
		cvShowImage( "Imagen en HSV", hsv_Image );
		cvWaitKey(0);
		cvReleaseImage(&hsv_Image);
		cvDestroyWindow( "Imagen en HSV" );
      }
}





/**
 * igual a segmentarImagen pero trabaja siempre sobre la imagen original.
 * La conversion de RGB a HSV la hace sobre la misma img
 */
void segmentarImagen2(IplImage* img,IplImage* mono_Image, int hlower,int hupper){
	uchar *data_hsv , *data_mono;




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

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

	/* DEBUG DE LA IMAGEN HSV*/
	printf("Datos de la imagen HSV\n");
	printf("height = %d\n",height);
	printf("width = %d\n",width);
	printf("step = %d\n",step);
	printf("channels = %d\n",channels);

	/* DEBUG DE LA IMAGEN MONO */
	printf("Datos de la imagen MONO\n");
	printf("step = %d\n",step_mono);
	printf("channels = %d\n",channels_mono);


	// Convertimos imagen RGB a HSV
    cvCvtColor(img,img,CV_RGB2HSV);

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

   // 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)){
							/*	DESCOMENTAR EL SIGUIENTE CODIGO PARA FILTRAR PRO SATURACION Y BRILLO */
							 // if (data_hsv[i*step+j*channels+1]>= Saturation) {
							//		if (data_hsv[i*step+j*channels+2]>= Brightness) {
									// Coloreamos el pixel en negro
							//		 data_mono[i*step_mono+j*channels_mono] = 255;
							//		} else {
									// Coloreamos el pixel en blanco
							//		  data_mono[i*step_mono+j*channels_mono] = 0;
							//		}
							//	} else {
								// Coloreamos el pixel en blanco
							//	  data_mono[i*step_mono+j*channels_mono] = 0;
							//	}
							data_mono[i*step_mono+j*channels_mono] = 255;
				//printf("negro\n");
            } else {
                // Coloreamos el pixel en blanco
                //printf("blanco\n");
                data_mono[i*step_mono+j*channels_mono] = 0;
            }
        } // fin del for j
      } // fin del for i

    cvNamedWindow( "Imagen en HSV", CV_WINDOW_AUTOSIZE );

    cvShowImage( "Imagen en HSV", img );

    cvWaitKey(0);


    cvDestroyWindow( "Imagen en HSV" );
}



// returns sequence of squares detected on the image.
// the sequence is stored in the specified memory storage
//color = 0 todos los colores, color = 1 rojo, color = 2 verde, color = 3 azul
CvSeq* findSquares4( IplImage* img, CvMemStorage* storage,int color,bool mono )
{
    CvSeq* contours;
    int i, c, l, N = 11;
    CvSize sz = cvSize( img->width & -2, img->height & -2 );
    IplImage* timg = cvCloneImage( img ); // make a copy of input image
    IplImage* gray = cvCreateImage( sz, 8, 1 );
    IplImage* pyr = cvCreateImage( cvSize(sz.width/2, sz.height/2), 8, 3 );
    IplImage* tgray;
    CvSeq* result;
    double s, t;
    // create empty sequence that will contain points -
    // 4 points per square (the square's vertices)
    CvSeq* squares = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvPoint), storage );

    // select the maximum ROI in the image
    // with the width and height divisible by 2
    cvSetImageROI( timg, cvRect( 0, 0, sz.width, sz.height ));

    // down-scale and upscale the image to filter out the noise
    if(!mono){
		cvPyrDown( timg, pyr, 7 );
		cvPyrUp( pyr, timg, 7 );
	}
    tgray = cvCreateImage( sz, 8, 1 );

	if(color==0){
		// find squares in every color plane of the image
		for( c = 0; c < 3; c++ )
		{
			// extract the c-th color plane
			cvSetImageCOI( timg, c+1 );
			cvCopy( timg, tgray, 0 );

			// try several threshold levels
			for( l = 0; l < N; l++ )
			{
				// hack: use Canny instead of zero threshold level.
				// Canny helps to catch squares with gradient shading
				if( l == 0 )
				{
					// apply Canny. Take the upper threshold from slider
					// and set the lower to 0 (which forces edges merging)
					cvCanny( tgray, gray, 0, thresh1, 5 );
					// dilate canny output to remove potential
					// holes between edge segments
					cvDilate( gray, gray, 0, 1 );
				}
				else
				{
					// apply threshold if l!=0:
					//     tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
					cvThreshold( tgray, gray, (l+1)*255/N, 255, CV_THRESH_BINARY );
				}

				// find contours and store them all as a list
				cvFindContours( gray, storage, &contours, sizeof(CvContour),
					CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0) );

				// test each contour
				while( contours )
				{
					// approximate contour with accuracy proportional
					// to the contour perimeter
					result = cvApproxPoly( contours, sizeof(CvContour), storage,
						CV_POLY_APPROX_DP, cvContourPerimeter(contours)*0.02, 0 );
					// square contours should have 4 vertices after approximation
					// relatively large area (to filter out noisy contours)
					// and be convex.
					// Note: absolute value of an area is used because
					// area may be positive or negative - in accordance with the
					// contour orientation
					if( result->total == 4 &&
						fabs(cvContourArea(result,CV_WHOLE_SEQ)) > 1000 &&
						cvCheckContourConvexity(result) )
					{
						s = 0;

						for( i = 0; i < 5; i++ )
						{
							// find minimum angle between joint
							// edges (maximum of cosine)
							if( i >= 2 )
							{
								t = fabs(angle(
								(CvPoint*)cvGetSeqElem( result, i ),
								(CvPoint*)cvGetSeqElem( result, i-2 ),
								(CvPoint*)cvGetSeqElem( result, i-1 )));
								s = s > t ? s : t;
							}
						}

						// if cosines of all angles are small
						// (all angles are ~90 degree) then write quandrange
						// vertices to resultant sequence
						if( s < 0.3 )
							for( i = 0; i < 4; i++ )
								cvSeqPush( squares,
									(CvPoint*)cvGetSeqElem( result, i ));
					}

					// take the next contour
					contours = contours->h_next;
				}
			}
		}
	}

    // release all the temporary images
    cvReleaseImage( &gray );
    cvReleaseImage( &pyr );
    cvReleaseImage( &tgray );
    cvReleaseImage( &timg );

    return squares;
}


// the function draws all the squares in the image
void drawSquares( IplImage* img, CvSeq* squares )
{
    CvSeqReader reader;
    IplImage* cpy = cvCloneImage( img );
    int i;

    // initialize reader of the sequence
    cvStartReadSeq( squares, &reader, 0 );

    // read 4 sequence elements at a time (all vertices of a square)
    for( i = 0; i < squares->total; i += 4 )
    {
        CvPoint pt[4], *rect = pt;
        int count = 4;

        // read 4 vertices
        CV_READ_SEQ_ELEM( pt[0], reader );
        CV_READ_SEQ_ELEM( pt[1], reader );
        CV_READ_SEQ_ELEM( pt[2], reader );
        CV_READ_SEQ_ELEM( pt[3], reader );

        // draw the square as a closed polyline
        cvPolyLine( cpy, &rect, &count, 1, 1, CV_RGB(0,255,0), 3, CV_AA, 0 );
    }

    // show the resultant image
    cvNamedWindow( "Cuadrados detectados", CV_WINDOW_AUTOSIZE );
    cvShowImage( "Cuadrados detectados", cpy );
    cvWaitKey(0);
    cvReleaseImage( &cpy );
}




bool hayRectangulo(IplImage* gray,  float minArea){
				CvMemStorage* storage = cvCreateMemStorage(0);
				
// find contours and store them all as a list
				CvSeq* contours;
				cvFindContours( gray, storage, &contours, sizeof(CvContour),CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0) );
				int s,i,t;
				// create empty sequence that will contain points -
				// 4 points per square (the square's vertices)
				CvSeq* squares = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvPoint), storage );
				// test each contour
				while( contours )
				{
					// approximate contour with accuracy proportional
					// to the contour perimeter
					CvSeq* result = cvApproxPoly( contours, sizeof(CvContour), storage,
						CV_POLY_APPROX_DP, cvContourPerimeter(contours)*0.02, 0 );
					// square contours should have 4 vertices after approximation
					// relatively large area (to filter out noisy contours)
					// and be convex.
					// Note: absolute value of an area is used because
					// area may be positive or negative - in accordance with the
					// contour orientation
					
					float area = cvContourArea(result,CV_WHOLE_SEQ);
					printf("Area del contorno = %f\n",area);
					if(fabs(area)>=minArea){
						printf("retorno true\n");
						cvReleaseMemStorage(&storage);
						return true;
					}
					if( result->total == 4 &&
						fabs(cvContourArea(result,CV_WHOLE_SEQ)) > 1000 &&
						cvCheckContourConvexity(result) )
					{
						s = 0;

						for( i = 0; i < 5; i++ )
						{
							// find minimum angle between joint
							// edges (maximum of cosine)
							if( i >= 2 )
							{
								t = fabs(angle(
								(CvPoint*)cvGetSeqElem( result, i ),
								(CvPoint*)cvGetSeqElem( result, i-2 ),
								(CvPoint*)cvGetSeqElem( result, i-1 )));
								s = s > t ? s : t;
							}
						}

						// if cosines of all angles are small
						// (all angles are ~90 degree) then write quandrange
						// vertices to resultant sequence
						if( s < 0.3 )
							for( i = 0; i < 4; i++ )
								cvSeqPush( squares,
									(CvPoint*)cvGetSeqElem( result, i ));
					}

					// take the next contour
					contours = contours->h_next;
				}
				cvReleaseMemStorage(&storage);
				return false;

}